I am trying to split this code in VB.net (owner_id) this is the data string.
yt.setConfig('DISTILLER_CONFIG', {"signin_url": "https:\/\/accounts.google.com\/ServiceLogin?hl=da\u0026continue=http%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Ddesktop%26feature%3Dcomments%26hl%3Dda%26next%3D%252Fall_comments%253Fv%253DZNW_uQaYfB0\u0026uilel=3\u0026passive=true\u0026service=youtube", "host_override": "https:\/\/plus.googleapis.com", "query": "http:\/\/www.youtube.com\/watch?v=ZNW_uQaYfB0", "channel_id": "UCe4LM_eKc9ywRmVuBm5pjQg", "first_time_comment_promo": false, "privacy_setting": "PUBLIC", "visible": true, "pinned_activity": null, "page_size": 100, "owner_id": "e4LM_eKc9ywRmVuBm5pjQg", "reauth": false, "video_id": "ZNW_uQaYfB0"});
So far I have tried this code, but it doesn't work. Already declared the owner_id string..
owner_id = (Split(data, """owner_id"": """)(1).Split("""")(0)
But it does not work.
EDIT:
How can I select the JSON into a string that I want to split from these scripts..?
http://pastebin.com/50bxc83T
This is JSON, string splitting it is not a great idea, but rather you should de-serialize the JSON into a class object using Json.NET, like this:
Public Class DistillerConfigResults
Public Property DISTILLER_CONFIG As DistillerConfig
End Class
Public Class DistillerConfig
Public Property signin_url As String
Public Property host_override As String
Public Property query As String
Public Property signin_url As String
Public Property channel_id As String
Public Property first_time_comment_promo As Boolean
Public Property privacy_setting As String
Public Property visible As Boolean
Public Property pinned_activity As Object
Public Property page_size As Integer
Public Property owner_id As String
Public Property reauth As Boolean
Public Property video_id As String
End Class
Now you can actually deserialize the JSON into your class object, like this:
Dim a As DistillerConfigResults = JsonConvert.DeserializeObject(Of DistillerConfigResults)(jsonString)
I would suggest using Regex:
"owner_id": "([\d\w]*)"
but only if you really want to parse this single key/value pair. If more should be extracted I would rather think about extracting JSON and deserializing it in normal way.
Working example:
Dim regex As Regex = New Regex("""owner_id"": ""([\d\w]*)""")
Dim match As Match = regex.Match("...here your string...")
If match.Success Then
Console.WriteLine(match.Groups(1).Value)
End If
if there are multiple parts like yt.Config(...) you can include the desired one identifier into regular expression, for example:
Dim regex As Regex = New Regex("yt.setConfig\('DISTILLER_CONFIG'.*""owner_id"": ""([\d\w]*)""")
Related
My requirement is to create a list of values inside application.properties file.
com.mail = aaaa, bbbb, cccc
I want to retrieve these values in my controller class and iterator over each value and should check with the requestbody/queryparam values which gets, when hitting an API
Consider I have an API
#RestController
#RequestMapping("/response")
public class HomeController {
#PostMapping("/postbody")
public String postBody(#RequestBody String fullName) {
//here I have to validate the fullName with the list I created in the application.properties
Eg: if(fullname.equals(aaaa) or if(fullname.equals(bbbb) or if(fullname.equals(cccc)
// I want to iterator over the list to check any value is matching with fullName.
}}
How to declare list of values inside application.properties? How to retrieve that list inside controller class? Post retrieving how to iterate over the list to check whether it matches with requestbody/queryparam value?
Please provide me with solution. Thank you
Split the list using a comma as the delimiter.
private String[] mailList;
public HomeController( #Value("${com.mail}") final String mail) {
mailList = mail.split(",")
}
You can now use mailList inside postBody method.
use comma separated values in application.properties
com.mail = aaaa, bbbb, cccc
Java code for access
#Value("${com.email}")
String[] mailList;
It worked.
In Application. properties you will add the parameter with values separated with ','
com.mail = aaaa,bbbb,cccc
in the controller will get the Values
#Value("${com.mail}")
private List<String> mailListValues;
#RestController
#RequestMapping("/response")
public class HomeController {
#Value("${com.mail}")
private List<Object> mailListValues;
#PostMapping("/postbody")
public String postBody(#RequestBody String fullName) {
if(!mailListValues.isEmpty()){
long countOfMatch = mailListValues.stream()
.filter(item->item.equals(fullName)).count();
if(countOfMatch >0)
// your Business .....
}
}}
please check images
A simplified version. I have two classes:
Public Class mSystem
Public Property ID as ObjectID
Public Property Name as string
End Class
Public Class mEmulator
Public Property ID as ObjectID
Public Property Name as string
<BsonRef("mSystems")>
Public Property AssociatedSystems as New List(Of mSystem)
End Class
Public Class Main
Public Sub EmaultorsLinkedToSystem
dim SelectedSystem as mSystem = db.Collections.mSystems.Find(Function(x) x.Name = "Sony Playstation").FirstOrDefault
test = db.Collections.mEmulators.Include(Function(x) x.AssociatedSystems).Find(Function(y) y.AssociatedSystems.Contains(SelectedSystem)).ToList
End sub
End Class
Now I know one mEmulator data object has "Sony Playstation" in its List(of mSystem). However, test returns null. Why isn't this finding it? I've tried a few permutations, but cant get this to work. Any ideas?
The Include method is used for resolving references to other collections, and you're not using BsonRef with AssociatedSystems (at least not in this example you provided). In your example, the instances of mSystem in AssociatedSystems are not being stored in a separate collection, but as an array of embedded documents in the emulators collection.
Try removing the Include call, it should work fine.
I'm trying to use the "RegularExpression" DataAnnotation validaiton in my model. My problem is even for the valid input I provide for the field containing the validation, the regex doesn't match and it fails.
I try to test the same valid input with the regex in a stand-alone console app and I find it gets through.
My point is, when regex is being used in dataannotation as validation, it considers all input as bad input. What am I missing here?
My regex is for checking comma-seperated email IDs. Here is my model:
public partial class BuildModel
{
public Int64 ConfigID { get; set; }
[Required(ErrorMessage = "Please select a stream!")]
public String Name{ get; set; }
[RegularExpression(#"^(([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*(;|,)\s*|\s*$))", ErrorMessage = "Please enter valid email IDs separated by commas")]
public string EmailIDs { get; set; }
public bool IsActive { get; set; }
}
Note: The "Required" data-annotation validation works just fine. It is just the Regex one, that won't work!
As far as i understand you just have problem within your Regex.
To validate emails separated by comma you can use this regex:
^( *[\w+-.%]+#[\w-.]+\.[A-Za-z]{2,4}( *, *)? *)+$
Check in in here.
You must the jquery.validate.min.js and jquery.validate.unobtrusive.min.js in your page without these libraries required annotation would not works.
I am using the regular expression for the Password field. Includes alpha-numeric string and md5.
[Required(AllowEmptyStrings = true)]
[RegularExpression(#"^(((?=.*\d)(?=.*[a-zA-Z]).{6,20})|([0-9a-f]{32}))$")]
[Display(Name = "Password")]
public string Password { get; set; }
And, I'd leave the field empty password. But ValidationMessage shows "This field is required."
message.Even if delete Required, it still gives the message.
Friends, how can I fix it?
Removing the Required attribute worked for me for server-side validation.
I've never used asp.net, and know nothing about it. However, 10 seconds on google tells me:
Make it nullable ( public string? Passsword { get; set; } )
We manage several ASP.NET MVC client web sites, which all use a data annotation like the following to validate customer email addresses (I haven't included the regex here, for readability):
[Required(ErrorMessage="Email is required")]
[RegularExpression(#"MYREGEX", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }
What I would like to do is to centralise this regular expression, so that if we make a change to it, all of the sites immediately pick it up and we don't have to manually change it in each one.
The problem is that the regex argument of the data annotation must be a constant, so I cannot assign a value I've retrieved from a config file or database at runtime (which was my first thought).
Can anyone help me with a clever solution to this—or failing that, an alternative approach which will work to achieve the same goal? Or does this just require us to write a specialist custom validation attribute which will accept non-constant values?
The easiest way is to write a custom ValidationAttribute that inherits from RegularExpressionAttribute, so something like:
public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute()
: base(GetRegex())
{ }
private static string GetRegex()
{
// TODO: Go off and get your RegEx here
return #"^[\w-]+(\.[\w-]+)*#([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$";
}
}
That way, you still maintain use of the built in Regex validation but you can customise it. You'd just simply use it like:
[Email(ErrorMessage = "Please use a valid email address")]
Lastly, to get to client side validation to work, you would simply add the following in your Application_Start method within Global.asax, to tell MVC to use the normal regular expression validation for this validator:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));
Checkout ScotGu's [Email] attribute (Step 4: Creating a Custom [Email] Validation Attribute).
Do you really want to put the regex in database/config file, or do you just want to centralise them? If you just want to put the regex together, you can just define and use constants like
public class ValidationRegularExpressions {
public const string Regex1 = "...";
public const string Regex2 = "...";
}
Maybe you want to manage the regexes in external files, you can write a MSBuild task to do the replacement when you build for production.
If you REALLY want to change the validation regex at runtime, define your own ValidationAttribute, like
[RegexByKey("MyKey", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }
It's just a piece of code to write:
public class RegexByKeyAttribute : ValidationAttribute {
public RegexByKey(string key) {
...
}
// override some methods
public override bool IsValid(object value) {
...
}
}
Or even just:
public class RegexByKeyAttribute : RegularExpressionAttribute {
public RegexByKey(string key) : base(LoadRegex(key)) { }
// Be careful to cache the regex is this operation is expensive.
private static string LoadRegex(string key) { ... }
}
Hope it's helpful: http://msdn.microsoft.com/en-us/library/cc668224.aspx
Why not just write you own ValidationAttribute?
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx
Then you can configure that thing to pull the regex from a registry setting... config file... database... etc... etc..
How to: Customize Data Field Validation in the Data Model Using Custom