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();
}
Related
I am trying to figure out if what I have so far is correct. Just feeling that I am chasing my own tail here, but I do feel that maybe I understand it correctly.
I have this file, where it includes a checksum that is oddly short. This is a set of two files, this one and the one I copied at pastbin under. I noticed that the first file includes the checksum, however it seems that if I change any parameter or the serial number the file will than fail to load.
I am correct to assume that the software looks for some of the xml values add in a string and create the checksum, and than compares it to the checksum in the file? I am not sure how they would have been able to add the checksum in the file itself otherwise, so I guess maybe it just takes some of the values.
Second, am I correct to assume that they just truncated the checksum? I never seen one that small.
In the end I am trying to figure out how to create my own checksum calibration but at the moment I am trying to at minimum understand how it works. Far from braking it :)
<?xml version="1.0" encoding="utf-8"?>
<InstrumentData xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/AcquisitionEngine.Types">
<CalibrationMode>parabolic</CalibrationMode>
<CalibrationTemperatures
xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:double>28</d2p1:double>
<d2p1:double>52</d2p1:double>
<d2p1:double>76</d2p1:double>
<d2p1:double>90</d2p1:double>
</CalibrationTemperatures>
<Checksum>6E23D45E</Checksum>
<ClusterSize>1</ClusterSize>
<HardwareVariant>Hardware_Legacy</HardwareVariant>
<InstrumentID>undefined</InstrumentID>
<LineFrequency>LineFrequency_50Hz</LineFrequency>
<MaxCalibrationDeviation>0.152</MaxCalibrationDeviation>
<SerialNo>6328ZG200015</SerialNo>
<Version>3.2</Version>
</InstrumentData>
The second file is included here https://pastebin.com/YQ1qKZ2v
Update: I have been able to find the code that generates this but I am still not getting the same hash.
private string GenerateChecksum(string serialno)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(this.HardwareVariant);
stringBuilder.Append(serialno);
return HashGenerator.GetHash32AsHex(stringBuilder.ToString());
}
From this line it seems to take the HadwareVariant and the serial number.
Than it seems to take this and generate a hash32 and than add an X2 at the end of it? My background is php, but am I understand this correct?
internal static class HashGenerator
{
private static HashAlgorithm CryptographicHasher;
static HashGenerator()
{
HashGenerator.CryptographicHasher = MD5.Create();
}
public static int GetHash32(string value)
{
byte[] bytes = Encoding.UTF8.GetBytes(value);
return
BitConverter.ToInt32(HashGenerator.CryptographicHasher.ComputeHash(bytes), 0);
}
public static string GetHash32AsHex(string value)
{
return HashGenerator.GetHash32(value).ToString("X2");
}
}
Just a quick question I got regarding HashMaps. Basically I have two strings. Both have a certain number of similar words in each string. The following HashMap method allows me to count how many times a certain word comes up in each sentence. My problem is returning this method in a main method. The HashMap method is the following:
public HashMap<String, Integer> getWordCounts(){
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < this.getWordArray().length; i++){
String key = getWordArray()[i];
Integer count = map.get(key);
if(count == null){
count = 1;
}else{
count++;
}
map.put(key, count);
}
return map;
}
This is what I've gotten so far for my return method.
HashMap<String, Integer> hashMapAdd = map.getWordCounts();
for(HashMap.Entry <String, Integer> entry : plato.entrySet()){
System.out.println(entry.getKey()+ "," + entry.getValue());
}
Am I going the right way with the return method? I feel like i'm going off into a wrong direction.
Thanks guys!
Besides the logic of the function(i have not analyzed it), about what you asked...
Yes, this method is perfectly alright to construct and return HashMap like this in Java, when i started working with java after working on C++ for 2 years, i also got confused sometimes, but than i understood that it is perfectly alright to return local objects in java, because garbage collector of JVM handles the issues which might occur in C++ using this technique.
Now, you got hashmap, to iterate through and print hashmap just use a loop like this:
for(String key:hashMapAdd.keySet())
System.out.println(key+ "," + hashMapAdd.get(key));
At least for me this is less confusing and easy.
For details of HashMap visit:
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
P.S: I have assumed that your code is compiling(you didn't complained any compilation errors), because the line map.getWordCounts(); seems suspicious, i have assumed that this method is in some class named map. But in that case you would not be able to make HashMap with Name map, you need to look why are you using map in this line of code.
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.
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);
}
I have the following route registered;
routes.MapRoute(
"LocationsByArea",
"Locations/{system}/{storage}/{area}",
new { controller = "StorageLocation", action = "Index" },
null
);
...and the following code in my view;
<%= Html.ActionLink("Platser", "Index", "StorageLocation", new { system = Model.System, storage = Model.Storage, area = item.Name }, null)%>
My problem is when the "area = item.Name" contains a colon, e.g. "Area 4:1". If I click the rendered link I get HTTP-error 400, Bad reqest. I guess I have to encode my area parameter in some way, but I cant figure out how. Any help is apreciated.
Thanks!
The built-in encoding/decoding does not work, so I suggest you roll your own, like this:
namespace MyProject.Helpers
{
public static class JobNameHelper
{
public static string JobNameEncode(string jobname)
{
return jobname.Replace(":", "---colon---");
}
public static string JobNameDecode(string jobname)
{
return jobname.Replace("---colon---", ":");
}
}
}
Can you not just use
Server.UrlEnconde(item.Name)
Or am I missing something?
In your routing you may have to use Server.UrlDecde as well although I think It should decode for you on request.
Try using the Routing Debugger to see what the url router is getting passed, then you can see where the decoding needs to happen
ASP.NET 3.5 SP1 and earlier have a number of restrictions on which URLs are valid. In ASP.NET 4 most of these issues have been fixes (or are at least customizable via web.config). I think that the colon character, even when encoded, might not be allowed in ASP.NET 3.5 SP1 and earlier due to security concerns. Allowing colons can be a security problem when performing file checks since they are a little-known syntax for NTFS Alternate Data Streams.
I recommend trying to choose a character other than a colon for these purposes. Maybe a comma, semi-colon, or equal sign might work instead?