WeekOfYear in X++ using .net lib - x++

static void Job5(Args _args)
{
int i;
System.DateTime netDttm;
System.Int32 intnet;
;
netDttm = new System.DateTime(2011,03,20 ,13,44,55);
intnet = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(netDttm, Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);
i = intnet;
info(int2str(i));
}
I tried the in vb.net it works fine but doing the same in x++(using .net lib) it shows syntax error..All I am trying is to get the week no. from a supplied date. Any insight would be appreciated.
P.S. I found another solution to this which is I created a dll file in VS .net and added this to Reference node(AOT)of AX. It has shorten the code in AX
static void Job5(Args _args)
{
weekofyear.wof asd;
;
asd = new weekofyear.Wof();
print asd.weekofyr(today());
pause;
}

try this
int i;
System.DateTime netDttm;
System.Int32 intnet;
System.Globalization.CultureInfo cultureInfo;
System.Globalization.Calendar calendar;
System.Globalization.CalendarWeekRule calWeekRule
;
netDttm = new System.DateTime(2011,03,20 ,13,44,55);
cultureInfo = System.Globalization.CultureInfo::get_CurrentCulture();
calendar = cultureInfo.get_Calendar();
intnet = calendar.GetWeekOfYear(netDttm, System.Globalization.CalendarWeekRule::FirstFourDayWeek, System.DayOfWeek::Sunday);
i = intnet;
info(int2str(i));

[Note to any future readers: The following described an error in the original code Indranil posted; it does not apply to the code currently in the question, because Indranil fixed this error. The other error was dealt with in another answer from someone else :-).]
You shouldn't be passing a string as the first argument to GetWeekOfYear; it wants a System.DateTime (http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx). (At least, that's true in ordinary .NET; I don't know whether Dynamics AX does some other magical thing. I doubt it does.)
(But if and when you do want a date in the form of a string, those backslashes \ should be forward slashes /.)

Just make sure you load the correct CultureInfo if you expect this code to support word wide locations. Loading the current CultureInfo will load the servers preferred culture. If the user is en-gb and the server is en-us, you first day of week will be incorrect.
To load a specific cultureinfo you can simply do this:
System.Globalization.CultureInfo arCul = new System.Globalization.CultureInfo("en-US");
In the example chosen as answer, the code loads cultureinfo, but the cultureinfo is not used as parameter to the GetWeekOfYear method, which doesnt really make any sense. Instead you could send in the settings from the cultureinfo.

Related

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IOrderedEnumerable

I am struggling with linq to get the datetime.
I am trying to get the info if the records are less than the current date
Here is the code:
public ActionResult _Events()
{
DateTime dt = DateTime.Now.Date;
var DocsFirst =(from t in db.tble_presentation
where dt >= EntityFunctions.TruncateTime(t.presentation_date)
select t).OrderByDescending(t => t.presentation_date).Take(2);
return PartialView(new Newsmodel
{
DocsList_list1 = DocsFirst,
});
}
but I get this following error
Cannot implicitly convert type 'System.Linq.IQueryable' to
'System.Linq.IOrderedEnumerable'. An explicit conversion exists
(are you missing a cast?)
thanks in advance
Hesh
It looks like DocsList_List1 is of type IOrderedEnumerable (as #Emre points out in the comment). To make the code compile, you either have to change the declaration of DocsList_list1 to be of a compatible type (probably IEnumerable) or make the result of the linq query an IOrderedEnumerable. An (somewhat ugly) way to do the latter:
var DocsFirst = (from t in db.tble_presentation
where dt >= EntityFunctions.TruncateTime(t.presentation_date)
select t).Take(2).AsEnumerable()
.OrderByDescending(t => t.presentation_date);
It's somewhat ugly because it does the ordering in memory instead of letting the database do it, but it still only reads the two requested elements thanks to Take(2) being placed before AsEnumerable().

T4MVC 2.6.65 and UseLowercaseRoutes=true error

Good day!
I'm using latest T4MVC from 2.6.65 from NuGet (upgraded from 2.6.64), I've set
// If true, use lower case tokens in routes for the area, controller and action names
static bool UseLowercaseRoutes = true;
And I got error:
The expression being assigned to '....' must be constant ...\T4MVC.cs
Here is the the generated code that triggers error:
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public class ActionNameConstants {
public const string Calc = ("Calc").ToLowerInvariant();
}
Is this a bug?
Ah sorry, the previous change broke it. I just pushed a new build of T4MVC (2.6.66) which addresses this. Well, it's more of a workaround as it basically doesn't generate the constant tokens when UseLowercaseRoutes is used. But that'll get us going for now.
The root of the problem is that C# doesn't support using .ToLowerInvariant() in constant strings. Ideally, it would just evaluate that at compile time, but it's not that smart :)

Biztalk mapping Date to String

I'm working on a biztalk project and use a map to create the new message.
Now i want to map a datefield to a string.
I thought i can do it on this way with an Function Script with inline C#
public string convertDateTime(DateTime param)
{
return System.Xml.XmlConvert.ToString(param,ÿyyyMMdd");
}
But this doesn't work and i receive an error. How can i do the convert in the map?
It's a Biztalk 2006 project.
Without the details of the error you are seeing it is hard to be sure but I'm quite sure that your map is failing because all the parameters within the BizTalk XSLT engine are passed as strings1.
When I try to run something like the function you provided as inline C# I get the following error:
Object of type 'System.String' cannot be converted to type 'System.DateTime'
Replace your inline C# with something like the following:
public string ConvertDateTime(string param1)
{
DateTime inputDate = DateTime.Parse(param1);
return inputDate.ToString("yyyyMMdd");
}
Note that the parameter type is now string, and you can then convert that to a DateTime and perform your string format.
As other answers have suggested, it may be better to put this helper method into an external class - that way you can get your code under test to deal with edge cases, and you also get some reuse.
1 The fact that all parameters in the BizTalk XSLT are strings can be the source of a lot of gotchas - one other common one is with math calculations. If you return numeric values from your scripting functoids BizTalk will helpfully convert them to strings to map them to the outbound schema but will not so helpfully perform some very random rounding on the resulting values. Converting the return values to strings yourself within the C# will remove this risk and give you the expected results.
If you're using the mapper, you just need a Scripting Functiod (yes, using inline C#) and you should be able to do:
public string convertDateTime(DateTime param)
{
return(param.ToString("YYYYMMdd");
}
As far as I know, you don't need to call the System.Xml namespace in anyway.
I'd suggest
public static string DateToString(DateTime dateValue)
{
return String.Format("{0:yyyyMMdd}", dateValue);
}
You could also create a external Lib which would provide more flexibility and reusability:
public static string DateToString(DateTime dateValue, string formatPicture)
{
string format = formatPicture;
if (IsNullOrEmptyString(formatPicture)
{
format = "{0:yyyyMMdd}";
}
return String.Format(format, dateValue);
}
public static string DateToString(DateTime dateValue)
{
return DateToString(dateValue, null);
}
I tend to move every function I use twice inside an inline script into an external lib. Iit will give you well tested code for all edge cases your data may provide because it's eays to create tests for these external lib functions whereas it's hard to do good testing on inline scripts in maps.
This blog will solve your problem.
http://biztalkorchestration.blogspot.in/2014/07/convert-datetime-format-to-string-in.html?view=sidebar
Regards,
AboorvaRaja
Bangalore
+918123339872
Given that maps in BizTalk are implemented as XSL stylesheets, when passing data into a msxsl scripting function, note that the data will be one of types in the Equivalent .NET Framework Class (Types) from this table here. You'll note that System.DateTime isn't on the list.
For parsing of xs:dateTimes, I've generally obtained the /text() node and then parse the parameter from System.String:
<CreateDate>
<xsl:value-of select="userCSharp:GetDateyyyyMMdd(string(s0:StatusIdChangeDate/text()))" />
</CreateDate>
And then the C# script
<msxsl:script language="C#" implements-prefix="userCSharp">
<![CDATA[
public System.String GetDateyyyyMMdd(System.String p_DateTime)
{
return System.DateTime.Parse(p_DateTime).ToString("yyyyMMdd");
}
]]>

How to autogenerate random password in asp.net mvc application?

No need to write it again... the question says it all.
You can use the built-in function included in the namespace System.Web.Security.
Membership.GeneratePassword Method
Generates a random password of the specified length.
Here's a nice article that might help you.
In the past I've done it once by using a piece of a Guid. I just created a new guid, converted it to a string and took the piece I wanted, I think I used the characters in the back, or the other way around.
Tested it with 100 loops and every time the string was different.
Doesn't has anything to do with MVC though...
public string CreatePassword(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}

Compare two RouteValueDictionary instances

I am writing a helper for my application which writes out a menu item for a given strongly typed controller/action as follows:
<%= Html.MenuLink<WhateverController>(c => c.WhateverAction(), "Whatever") %>
As part of this process, I would like to apply the class of active to the outputted link if the current page and the page linked to are the same. I figure the best way of doing it is to compare the contents of the RouteValueDictionary for the current request to that of the result of the Expression given to the helper method. However, I cannot figure out a good way of comparing whether the items in the two RouteValueDictionarys are the same.
Is there a simple way of doing this? I effectively want to complete it in the following way:
public static string MenuLink<T>(this HtmlHelper html, Expression<Action<T>> action, string linkText) where T : Controller
{
// var link = html.ActionLink<T>(action, linkText, new {}); // Not important yet
var routeValues = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression<T>(action); // Might change?
var currentRouteVals = html.ViewContext.RouteData.Values;
bool isActivePage = /* are the contents of routeValues also
inside currentRouteValues? */
var tb = new TagBuilder("li");
// Continues...
}
I have tried using the built-in comparison (==), but it seems that it is using the default equality implementation and therefore returns false since they are not the same instance. I have also tried the following:
bool isActivePage = routeValues.All(x => currentRouteVals.ContainsValue(x));
but that doesn't work either. Am I completely barking up the wrong tree?
Bah, I post the question and then figure out the answer. Am posting here in case anyone else faces this problem. The line I needed was as follows:
bool isActivePage = routeValues.All(x => x.Value.ToString() == (currentRouteVals[x.Key].ToString()));
Turns out it was originally comparing them as objects, not as strings. Converting them to strings compares them as one would hope, and now all is well.
It should be noted that they should be compared around this way. If they are compared round the other way, the RouteValueDictionary may contain things other than those you care about (such as an "id" value). Or at least that's how I understand it at the moment. Further experimentation may require me to revisit this...
I just encountered the same problem and was looking at the accepted answer and noticed it would:
cause an exception if the key didn't exist in the second routeValues list
is case sensitive which generally isn't the case for Microsoft URIs.
if the key is in the second list but not the first list the lists would compare as being the same which is incorrect.
This solution resolves the mentioned issues as a self contained extension method off of RouteValueDictionary:
public static bool AreEqual(this RouteValueDictionary rvdA, RouteValueDictionary rvdB)
{
var Equal =
new Func<RouteValueDictionary, RouteValueDictionary, bool>((a, b) => a.All(kvp =>
{
object val = b[kvp.Key];
return val != null && kvp.Value.ToString().Equals(val.ToString(), StringComparison.InvariantCultureIgnoreCase);
}));
return rvdA.Count == rvdB.Count && Equal(rvdA, rvdB) && Equal(rvdB, rvdA);
}

Resources