Saturday, 29 September 2018

c# - NullReferenceException in DbContext.saveChanges()



Taking my very first babysteps with Entity Framework 5.0, I run into an exception with the very first Entity I create.




Please note that every table created after that works just fine. Also, do note that I've taken the usual steps of regenerating the database and/or restarting the Visual Studio IDE.



Using Model-First, I created a trivial table called Contacts, defined as



  









I then tried to run the following code (from the Page_Load of an ASP.NET page)



            var contact = new DataContext.Contact { Name = aName };

context.Contacts.Add(contact);
context.SaveChanges();



(with aName != null)



Exception:



System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=System.Web
StackTrace:

at System.Web.UI.ParseChildrenAttribute.GetHashCode()
at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.HashSet`1.InternalGetHashCode(T item)
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(Type type)
at System.Data.Entity.ModelConfiguration.Utilities.AttributeProvider.GetAttributes(PropertyInfo propertyInfo)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildPropertyValidator(PropertyInfo clrProperty)

at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildValidatorsForProperties(IEnumerable`1 clrProperties, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildTypeValidator[T](Type clrType, IEnumerable`1 edmProperties, IEnumerable`1 navigationProperties, Func`3 validatorFactoryFunc)
at System.Data.Entity.Internal.Validation.EntityValidatorBuilder.BuildEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.Validation.ValidationProvider.GetEntityValidator(InternalEntityEntry entityEntry)
at System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items)
at System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items)
at System.Data.Entity.DbContext.GetValidationErrors()
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()

at Contactisch._Default.AddContact(String aName) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 32
at Contactisch._Default.Page_Load(Object sender, EventArgs e) in c:\Projects\Contactisch\Contactisch\Contactisch\Default.aspx.cs:line 14
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:


Can someone explain the cause of this exception ? Especially, what is that call to ParseChildrenAttribute.GetHashCode doing there?




I did find someone running into the same issue here, but no satisfactory explanation was given.


Answer



Problem solved.



The cause was a bit silly. I was using the default ASP.NET Web Forms Application project from VS Web Express to perform my testing. This project contains a web form called Contact.aspx, so it already includes a partial class Contact in the same namespace as my Contact entity.



Understandably, this didn't play well with Entity Framework, leading to the rather obscure error above. Deleting the aspx page solved the problem.


regex - The meaning of \1* operator in Java regexes




I am learning about Java regexes, and I noticed the following operator:



\\*1


I'm having hard time figuring out what it means (searching in the web didn't help).
For example, what is the difference between these two options:



    Pattern p1 = Pattern.compile("(a)\\1*"); // option1

Pattern p2 = Pattern.compile("(a)"); // option2

Matcher m1 = p1.matcher("a");
Matcher m2 = p2.matcher("a");

System.out.println(m1.group(0));
System.out.println(m2.group(0));


Result:




a
a


Thanks!


Answer



\\1 is back reference corresponding in this case to the first capturing group which is (a) here.



So (a)\\1* is equivalent to (a)a* in this particular case.




Here is an example that shows the difference:



Pattern p1 = Pattern.compile("(a)\\1*");
Pattern p2 = Pattern.compile("(a)");

Matcher m1 = p1.matcher("aa");
Matcher m2 = p2.matcher("aa");

m1.find();

System.out.println(m1.group());
m2.find();
System.out.println(m2.group());


Output:



aa
a



As you can see when you have several a the first regular expression captures all the successive a while the second one captures only the first one.


Interpolation (double quoted string) of Associative Arrays in PHP



When interpolating PHP's string-indexed array elements (5.3.3, Win32)
the following behavior may be expected or not:




$ha = array('key1' => 'Hello to me');

print $ha['key1']; # correct (usual way)
print $ha[key1]; # Warning, works (use of undefined constant)

print "He said {$ha['key1']}"; # correct (usual way)
print "He said {$ha[key1]}"; # Warning, works (use of undefined constant)

print "He said $ha['key1']"; # Error, unexpected T_ENCAPSED_AND_WHITESPACE
print "He said $ha[ key1 ]"; # Error, unexpected T_ENCAPSED_AND_WHITESPACE

print "He said $ha[key1]"; # !! correct (How Comes?)


Inerestingly, the last line seems to be correct PHP code. Any explanations?
Can this feature be trusted?





Edit: The point of the posting now set in bold face in order to reduce misunderstandings.

Answer



Yes, you may trust it. All ways of interpolation a variable are covered in the documentation pretty well.




If you want to have a reason why this was done so, well, I can't help you there. But as always: PHP is old and has evolved a lot, thus introducing inconsistent syntax.


mysql - Multibyte SQL injection

This is so often discussed issue, I know, but I've recently found this vulnerability and I'm testing whether I'm resistant to such an injection, however I'm not able to simulate that behavior. Probably, I don't understand that query they're using.



The part that interests me:





The first vulnerability affects the mysql_real_escape_string()
function family which does not reject invalid multi-byte characters.
For example, in UTF-8, the "0xC8 ' ' attackersql" or "0xC8 \ '
attackersql" string is converted to "one_character ' attackersql"
(ignore spaces). So, the query:



SELECT ... WHERE v = ' mysql_real_escape_string("0xC8 ' attackersql") '



become :




SELECT ... WHERE v = ' 0xC8 ' ' attackersql '



SELECT ... WHERE v = 'one_character ' attackersql'



An attacker can therefore inject the attackersql command.




The question sounds pretty lame, but how can I make this injection work?



Note (edited): I'm using PHP 5.2.6, MySQL 5.0.51a (correction) and charset 'utf8' is set on DB connection.

Java String trim has no effect




Java String trim is not removing a whitespace character for me.



String rank = (some method);
System.out.println("(" + rank + ")");


The output is (1 ). Notice the space to the right of the 1.



I have to remove the trailing space from the string rank but neither rank.trim() nor rank.replace(" ","") removes it.




The string rank just remains the same either way.



Edit: Full Code::



Document doc = Jsoup.connect("http://www.4icu.org/ca/").timeout(1000000).get();
Element table = doc.select("table").get(7);
Elements rows = table.select("tr");
for (Element row: rows) {
String rank = row.select("span").first().text().trim();

System.out.println("("+rank+")");
}


Why can't I remove that space?


Answer



The source code of that website shows the special html character  . Try searching or replacing the following in your java String: \u00A0.



That's a non-breakable space. See: I have a string with "\u00a0", and I need to replace it with "" str_replace fails




rank = rank.replaceAll("\u00A0", "");


should work. Maybe add a double \\ instead of the \.


regex - how to use sed, awk, or gawk to print only what is matched?




I see lots of examples and man pages on how to do things like search-and-replace using sed, awk, or gawk.



But in my case, I have a regular expression that I want to run against a text file to extract a specific value. I don't want to do search-and-replace. This is being called from bash. Let's use an example:



Example regular expression:



.*abc([0-9]+)xyz.*



Example input file:



a
b
c
abc12345xyz
a
b
c



As simple as this sounds, I cannot figure out how to call sed/awk/gawk correctly. What I was hoping to do, is from within my bash script have:



myvalue=$( sed <...something...> input.txt )


Things I've tried include:



sed -e 's/.*([0-9]).*/\\1/g' example.txt # extracts the entire input file
sed -n 's/.*([0-9]).*/\\1/g' example.txt # extracts nothing


Answer



My sed (Mac OS X) didn't work with +. I tried * instead and I added p tag for printing match:



sed -n 's/^.*abc\([0-9]*\)xyz.*$/\1/p' example.txt


For matching at least one numeric character without +, I would use:



sed -n 's/^.*abc\([0-9][0-9]*\)xyz.*$/\1/p' example.txt


Friday, 28 September 2018

CSS3 FLEXBOX, left and right floating items



flex item 1

flex item 2

flex item 3




In above example i want Item1 on left side, and, item 2 and 3 on right side of page using CSS3 Flexbox.



Thanks in advance

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...