I can't see the wood for the trees.
Why is this throwing a String Format Exception?
private const string GoogleAnalyticsFormat = #"<script type=""text/javascript"">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{0}']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>";
public static IHtmlString RenderGoogleAnalytics<T>(this HtmlHelpers<T> html, string trackingCode )
{
return html.Raw(string.Format(GoogleAnalyticsFormat, trackingCode));
}
Look at this bit of your format string:
function () { ... }
Those braces are being interpreted as the start/end of placeholders. You need to double them:
function () {{ ... }}
So your complete declaration would be:
private const string GoogleAnalyticsFormat = #"<script type=""text/javascript"">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '{0}']);
_gaq.push(['_trackPageview']);
(function () {{
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
}})();
</script>";
You have to change braces { to {{
Related
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.
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.
The return result of string list is :
var result= "1,red,2,blue,3,green,4,orange";
I want to use a loop and get result like 1,2,3,4 and red,blue,green,orange
My code is as below.
I got the error in split.
Object does not support for split().
I am using jquery 1.10.1 .
$.ajax({
type: "GET",
url: "/_vti_bin/userService/myservice.svc/GetUserListForMentionSign?query" + query,
async: false,
dataType: "JSON",
cache: false,
processdata: true,
success: function (result) {
data = result;
//arrary
var resultArray = data.Split(',');
var id = new Array(), name = new Array();
$.each(resultArray, function (index, value) {
if (isNaN(value)) {
name.push(value);
alert(name.push(value));
}
else {
id.push(value);
}
});
Here is the web service for c#.
public List<string> GetUserListForMentionSign(string username)
{
List<User> UserList = new List<User>();
List<string> returnvalue=new List<string>();
try
{
string returnstring = string.Empty;
DataTable dt = null;
dt = Library.Helper.FindUser(username, 200);
foreach (DataRow dr in dt.Rows)
{
if (dr["Title"].ToString() != "Person.aspx") // those user without the name
{
User user = new User();
user.id = dr["ID"].ToString();
user.name = dr["Name"].ToString();
UserList.Add(spuser);
}
}
}
catch (Exception ex)
{
}
return UserList.Select(a=>new[]{ a.name.ToString(),a.id.ToString()}).SelectMany(a=>a).ToList();
}
You can use jQuery map function to create 2 different arrays containing even and odd indexed values and manipulate it
var result = "1,red,2,blue,3,green,4,orange";
var arr=result.split(',');
var odd = jQuery.map( arr, function(n,i){
return i%2 ? n : null;
});
var even = jQuery.map( arr, function(n,i){
return i%2 ? null : n;
});
Try this : Use .split() to convert string into array and then iterate array. Inside loop check if value is number of not using isNaN() and push values to respective array.
var result= "1,red,2,blue,3,green,4,orange";
var resultArray = result.split(",");
var numberArray = new Array(), colorArray = new Array();
$.each(resultArray , function( index, value ) {
if(isNaN(value))
colorArray.push(value);
else
numberArray.push(value);
});
alert(colorArray.toString());
alert(numberArray.toString());
try
var result = "1,red,2,blue,3,green,4,orange";
var splitValue = result.split(",");
var num = [];
var str = [];
for (var i in splitValue) {
if (i % 2 === 0) {
num.push(splitValue[i]);
} else {
str.push(splitValue[i]);
}
}
console.log(num);
console.log(str);
In C language I have implemented like this.
Logic: input is parsed to split num&strings and stored to different array. At the end result array is printed.
int main()
{
char *str, result []= "1,red,2,blue,3,green,4,orange";
char *p, *p1;
char num[10], i=0;
char name[10][15], j=0,k;
str =result;
while (1)
{
p= strchr (str, ',');
if(!p1)
break;
num [i]=atoi (p-1) ;
i++;
p1= strchr (p+1, ',');
if(!p1){
strcpy ( name[j], p+1);
j++;
break;
}
p1[0]='\0';
strcpy ( name[j], p+1);
j++;
str=p1+1;
}
for (k=0; k<i; ++k){
printf ( "%d ", num[k]);
}
printf ("\n");
for (k=0; k<j; ++k){
printf ( "%s ", name[k]);
}
printf ("\n");
}
var result= "1,red,2,blue,3,green,4,orange";
string[] arr = result.Split(',');
int[] num;
string[] text;
foreach(var i in arr)
{
int cont;
if (int.TryParse(i, out cont) == false)
text[] = i;
else
num[] = cont;
}
or loop manually
for(int i = 0; i < arr.lenght; i++)
{
int cont;
if (int.TryParse(arr[i], out cont) == false)
text[i] = i;
else
num[i] = cont;
}
note : splitting from server side for C#.
I have a javascript code that works wonderfully:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
alert("Max reached");
}
document.getElementById(field).innerHTML = maxWords - wordCount;
}
</script>
how do i replaced the alert("Max reached") so that it shows the validation message for the textarea that i am checking:
#Html.ValidationMessageFor(model => model.description)
can i do this:
<script type="text/javascript">
var maxWords = 100;
function limitLengthInWords(field)
{
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
if (wordCount >= maxWords)
{
field.value = value.match(re);
#Html.ValidationMessageFor(field,"Max reached");
}
document.getElementById(field).innerHTML = maxWords - wordCount;
}
</script>
The easiest way would be to have a some hidden text that you show.
<span style="display:none;" class="max-reached">Max Reached</span>
$(".max-reached").show()
Alternatively try using a library that does this and includes a countdown. Such as NobleCount
Make sure you have your model annotated correctly, i am using password property as an example
[StringLength(30, ErrorMessage = "Error Message")]
public string Password
{
get;
set;
}
Change this #Html.ValidationMessageFor(field,"Max reached");
to I am assuming $(field) is the id such as $('#Password') all you have to do is access the data information stored by mvc $(field).data('val-length')
I'm download web page and parse javascript code, which have in code hash and java decode function...
please I want to call javascript decode method from C# program...
In web page I've :
window.decoded_hashes = {};
window.decodehash = function(hash) {
window.dec_hash(hash);
return window.decoded_hashes[hash];
window.dec_hash = function(hash) {
(function(__){window.decoded_hashes[hash] = _(__,8,_____(__)-12)+_(__,0,5);})((function(__){____='';for(___=0;___<_____(__);++___)____+=______(__,_____(__)-___-1);return window[_______(88,11,-13)]?__:____;})((function(__){____=window[_______(103,-2)]?'':'____';for(___=0;___<_____(__);++___)____+=(function(__){return __>111?(121-__):_______(__);})(__.charCodeAt(___));return ____;})((function(__){_______=function(){var _='',__=0,___=arguments;for(var ____=0;____<___.length;++____)_+=String.fromCharCode(__+=___[____]);return _;};______=function(__,___){return __.charAt(___);};_____=function(__){return __.length;};____=(_=function(_,__,___){____='';(___=___?___:(_____(_)-__));for(;___;--___)____+=(function(_,__){return ______(_,__)})(_,__++);return ____;})(__,3,3);____+=_(__,0,2)+_(__,8);return ____;})(hash))));
}
window.wall_post_hash = decodehash('tsucuqtyqvedvvpruuqasavdpwdcxafcystrdfvsyd');
And I must sent decode hash on server... hash in () - dinamic
How to make easier? I've found Rhino and IKVM, but have not understood yet...
Give me advice Pls...
Sorry for my English;)
You could include Microsoft.JScript in your project references.
Check out an example from Rick Strahl's on how you can use Eval to get your results.
Here's an implementation I managed to work out after some debugging and changes. It returns the same result as your example. One issue is that .Net don't seem to work with the function "arguments" variable. So I added 5 variables to that function to get it to work. Seems the most which is passed is 3.
package Pack
{
class JSEval
{
public function MyEval(inputhash : String) : String
{
var ___ = 0;
var _= '';
var ____ = '';
var _______;
var ______;
var _____;
var ____ = (_ = function(_, __, ___) {
____ = '';
(___ = ___ ? ___ : (_____(_) - __));
for (; ___; --___) ____ += (function(_, __) {
return ______(_, __)
})(_, __++);
return ____;
})
var mywin = new Object();
mywin.decoded_hashes = {};
mywin.dec_hash = function(hash) {
(function(__) {
mywin.decoded_hashes[hash] = _(__, 8, _____(__) - 12) + _(__, 0, 5);
})((function(__) {
var ____ = '';
for (___ = 0; ___ < _____(__); ++___) ____ += ______(__, _____(__) - ___ - 1);
return mywin[_______(88, 11, -13)] ? __ : ____;
})((function(input) {
var res = mywin[_______(103, -2)] ? '' : '____';
for (var i = 0; i < _____(input); ++i) res += (function(input) {
return input > 111 ? (121 - input) : _______(input);
})(input.charCodeAt(i));
return res;
})((function(__) {
_______ = function(a,b,c,d,e) {
var arguments = new Array();
if( a != undefined )
arguments.push(a);
if( b != undefined )
arguments.push(b);
if( c != undefined )
arguments.push(c);
if( d != undefined )
arguments.push(d);
if( e != undefined )
arguments.push(e);
var _ = '';
var __ = 0;
for (var i = 0; i < arguments.length; ++i) _ += String.fromCharCode(__ += arguments[i]);
return _;
};
______ = function(__, ___) {
return __.charAt(___);
};
_____ = function(__) {
return __.length;
};
____ = (_ = function(_, __, ___) {
____ = '';
(___ = ___ ? ___ : (_____(_) - __));
for (; ___; --___) ____ += (function(_, __) {
return ______(_, __)
})(_, __++);
return ____;
})(__, 3, 3);
____ += _(__, 0, 2) + _(__, 8);
return ____;
})(hash))));
}
mywin.decodehash = function(hash) {
mywin.dec_hash(hash);
return mywin.decoded_hashes[hash];
}
return mywin.decodehash(inputhash);
}
}
}