SOFTWARE DEVELOPMENT 7th LECTURE Reminder Deadline next week - - PowerPoint PPT Presentation
SOFTWARE DEVELOPMENT 7th LECTURE Reminder Deadline next week - - PowerPoint PPT Presentation
SOFTWARE DEVELOPMENT 7th LECTURE Reminder Deadline next week (week 8) So far things are... Today Working with Strings Formatting values Data validation Working with data collections Reflection Dynamic
Reminder
- Deadline – next week (week 8)
- So far things are...
Today
- Working with Strings
- Formatting values
- Data validation
- Working with data collections
- Reflection
- Dynamic
- Attributes
String
- String – immutable reference type
– When using Replace or ToUpper a reference to newly created string is returned.
- Intern pool:
– For optimal work, CLR saves references to unique string type values in intern pool. – Different String type variables with same values points to same adress in the intern pool.
- Common ways of creation:
– By assigning specific value – Reading from element (like TextBox or ComboBox) – By assigning operation result.
Immutable types
- Makes it easy for concurent programming:
– Main problem – how threads are accessing resources? – E.g. – race conditions.
- string – immutable type:
Comparing strings
- What will be printed out?
- True
Working with String
- What will be printed out?
- False
- True
Working with String
- Main constructors:
– By giving char array – By giving char array with starting and ending indexes – By giving char and repetition count:
- Properties:
– Empty – Length – Read-only indexer
- To change specific chars, one needs to convert to char array or use Replace method(s)
String.Empty vs „“ vs null
- String.empty:
– read-only constant. – Used when creating String variable, when it's not clear, when value will appear. – Not possible to use with Case and Deault:
- „“
– Constant created on compile time – "" == string.Empty
- null
– no reference at all.
String methods
Method Description
Compare Compares two Strings and returns –1, 0, or 1 to indicate that the first String should be considered before, equal to, or after the second String in the sort order. Concat Takes as a parameter an array of Strings or other objects and returns a String holding the concatenation of the objects. Copy Returns a copy of the String. Equals Returns true if two Strings have the same value. Format PUses a format string and a series of objects to generate a formatted text string. IsNullOrEmpty Returns true if the String holds a blank string "" or the String variable refers to
- null. All true:
string value1 = ""; string value2 = String.Empty; string value3 = null; IsNullOrWhiteS pace Returns true if the String variable holds a blank string, refers to null, or holds only whitespace characters. Whitespace characters are those for which Char.IsWhiteSpace returns true. Join Joins the values in an array of strings or other objects separated by a separator string. string[] weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; string allDays = string.Join(",", weekdays);
String instance methods
- Comparing:
– CompareTo (in order) and Equals (for equality)
- Substring search:
– Contains, EndsWith, StartsWith
- Index finding:
– IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny
- Changing the value:
– ToUpper, ToLower, Insert, Remove, Replace – Space changing and etc.: Trim, TrimEnd, TrimStart, PadLeft, PadRight
- Convert to array:
– CopyTo, ToCharArray, Split
String: special symbols
- \'
- \"
- \\
- \0 - Unicode 0
- \n - new line (character 10)
- \r - return (character 13)
Fun facts
- Space in memory:
– 20+(n/2)*4 – Saved in memory:
- Array of char size
- String size
- Char values
- Similar to... arrays :)
StringBuilder
- Working with String is slow, since it's immutable
- Self-study:
– How slow - string.cs
- How to avoid:
StringBuilder: props and methods
Property Description Capacity Gets or sets the number of characters that can be held by the StringBuilder. If the amount of text stored in the StringBuilder exceeds this amount, the object allocates more space. If you know the StringBuilder needs to hold at least a certain number of characters, you can use this property to make the object pre- allocate memory instead of allocating memory incrementally.. Length Gets or sets the current number of the characters stored. Cuts if lower. Method Description Append Appends a string representation of an object to the end AppendFormat Formats a series of objects and appends the result to the end EnsureCapacity Ensures that the StringBuilder has at least a given capacity Insert Inserts a string representation of an object at a given position Remove Removes a range of characters from the StringBuilder’s text Replace Replaces all instances of a character or string with a new ToString Returns a normal String representation of the StringBuilder’s text
Formating data
- ToString
– Class Object has ToString() method, all other classes inherts it. – Standard method behavior – print out object type,
- Most of the time it is overloaded
– For double value of 5.25 ToString() returns „5.25“. – For double value of 5.25 ToString() returns „05.250“. – What will be printed out? – Answer in ToString.cs – Extra info: Custom Numeric Format Strings (MSDN)
Formating data
- Repetition:
- For numeric types (FormatString):
Directive Description Example C or c Currency $12,345.67 D or d Decimal (integer types only) 12345 E or e Scientific notation 1.234567E+004 F or f Fixed-point 12345.67 G or g Default General (fixed-point or scientific, whichever is shorter) 12345.67 N or n Number (with decimal and thousands separators) 12,345.67 P or p Percent (multiplied by 100 and % added) 0.12 becomes 12.00 % X or x Hexadecimal (integer types only) 3039
Formating data
- String.Format
– For each object to be formated this syntax applies: {index[,length][:formatString]}
– {0} first argument, with standard formatting – {1,4} second argument, which will take at least four spaces – {2:X} third argument with HEX format – What will be printed if i == 97?
Formating data
string name = "Mark"; var date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now."); // Both calls produce the same output that is similar to: // Hello, Mark! Today is Wednesday, it's 19:40 now.
Formating data
- Date and time:
- Other methods:
– ToShortDateString, ToLongDateString, ToShortTimeString, ToLongTimeString.
Letter Description Example d Short date 3/14/2014 D Long date Friday, March 14, 2012 f “Full” with short time Friday, March 14, 2012 2:15 PM F “Full” with long time Friday, March 14, 2012 2:15:16 PM g “General” with short time 3/14/2014 2:15 PM G “General” with long time 3/14/2014 2:15:16 PM m or M Month/day March 14 t Short time 2:15 PM T Long time 2:15:16 PM y or Y Year/month March, 2014
Data validation
- Data validation – checking, if inputed data is correct.
- Ideally, we would catch it as soon as possible.
- Best way – avoid it at all, for example:
– numericUpDown – DateTimePicker – Etc.
- It helps avoid not only checking, but spaming the user as well.
Regex
- Regular expression (regex) allows:
– Determine, if given string matches the pattern, which is called regular expression. – Find parts of the string matching the pattern. – Change parts of the string matching the pattern.
- Main class:
– System.Text.RegularExpressions.Regex
- More - in the course of internet technologies.
Regex methods
Method Description IsMatch Returns true if a regular expression matches a string. Match Searches a string for the first part of it that matches a regular expression. Matches Returns a collection giving information about all parts of a string that match a regular expression. Replace Replaces some or all the parts of the string that match a pattern with a new
- value. This is more powerful than the string class’s Replace method.
Split Splits a string into an array of substrings delimited by pieces of the string that match a regular expression
Regex exmples
- Does string have more than one digit?
Return those digits:
Regex
- For pattern we need to escape - “\”:
– C# reads „\“ as a special char – So to print "\n" you need to escape the "\"
- Console.WriteLine(„testas\\ntestas")
- Console.WriteLine(@" testas\ntestas");
– Most common ones are: \n ir \t
Regex: anchors
- Anchors define, where pattern should be matched
- Multiline is to be considered
- Main ones:
Anchor Description ^
String start, or new line in multiline.
$
String end, or end of line in multiline.
\A
Line start
\Z
Line end
Regex: simple example
- pattern = @"^\d{3}-\d{4}$";
Part Description ^ Defines start of the string. \d Any digit {3} Repeats last part 3 times – Matches symbol „-“ \d Any digit {4} Repeats last part 4 times
Regex: symbols
Constr. Description [chars] Matches a single character inside the brackets. For example, [aeiou] matches a lowercase single vowel. [^chars] Matches a single character that is not inside the brackets. For example, [^aeiouAEIOU] matches a single nonvowel character such as x, 7, or &. [first-last] Matches a single character between the character first and the character last. For example, [a- zA-Z] matches any lowercase or uppercase letter. . A wildcard that matches any single character except \n. (To match a period, use the \. escape sequence.) \w Matches a single word character. Equivalent to [a-zA-Z_0-9]. \W Matches a single nonword character. Equivalent to [^a-zA-Z_0-9]. \s Matches a single whitespace character. Normally this includes space, form feed, newline, return, tab, and vertical tab. \S Opposite to \s \d
- Digit. [0-9].
\D Opposite to \d. [^0-9].
Regex: settings
- Kviečiant Regex klasės metodus, galimi tokie nustatymai (pagrindiniai):
- Is defined like:
- More in MSDN: Regular Expression Options
Enum Short. Description
IgnoreCase
i Ignore case
Multiline
m Use multiline. ^ and $ works with lines within string.
Singleline
s Single line mode. "." detects \n as well.
IgnorePattern Whitespace
x Ignore spaces in pattern
RightToLeft
None Changes search direction
Regex: counters
- Lets define how many instances of detected symbol we want.
- For example \d{3} matches any three digits.
- Examples:
– Matches("book book", "bo+") returns two „boo“ – Matches("book book", "bo+?") returns two "bo", as "?" returns the least possible
Counter Description * Last element 0 or more time. + Last element 1 or more time. ? Last element 0 or 1 time. {n} Last element n times {n,} Last element n or more times {n,m} Last element between n and m times
Regex: other examples
- ^[2-9][0-9]{2}-\d{4}$:
– Start: NXX where N is a digit 2–9, X is 0–9. – middle: - – end: 4 digits
- ^([2-9][0-8]\d-)?[2-9][0-9]{2}-\d{3}$:
– ? shows, that () part can be 0 or more times.
- ^\d{5}(-\d{4})?$:
– 12345 or 12345-6789 are matches
Regex: other examples
- ^[A-Z]\d[A-Z]\d[A-Z]\d$:
– Matches: ABABAB where A is any CAPS, B is a digit.
- ^[a-zA-Z0-9_%+-]+
– String has to start with given symbols and repeat itself 1 or more times.
Array
- Array is a reference type
- Zero-indexed, so last element index and size does not match!
- Main properties: Length and Rank (dimension count)
- What will be printed out?
Array
- Data copy-paste (both in shallow way):
– clone: – What will be printed? – copyTo: copy-paste to given array, index can be given.
Data collections
- More capabilities than array
- Main:
– List and List<T> – Dictionary and Dictionary<T> – Stack – Queue
- Namespace:
– System.Collections – System.Collections.Generic – System.Collections.Concurrent
System.Collection.ArrayList
- Collection of varying size, which can hold any types.
- Main difference from array – dynamic size.
- Method Add:
– Takes object type as parameter. – Thanks to boxing/unboxing any types are possible: – Main properties:
- Capacity – defines how many elemens can fit
- Count – how many elements are right now.
- Item – gets or sets value at given index.
System.Collection.ArrayList
Metodas Aprašymas Add Adds element in the end AddRange Adds elements in the end BinarySearch Returns the index of given value. Works only if elements are sorted and implements IComparable. Clear Clears all elements. Contains Checks, if given element exists CopyTo Copy-paste to one dimensional array IndexOf Returns index of the first instance of given value Insert Inserts element at given index, while others are shifted. Remove Removes given element RemoveAt Removes given element at given index Reverse Reverses the order of all elements Sort
- Sorts. Elements must implement IComparable
System.Collection.HashTable
- Collection with key/value pairs, which is of dynamic size and can save any
- bjects
– What potential problem does it cause?
- Values (e.g. data) is stored by key, not by index:
System.Collection.Queue
- FIFO (first-in-first-out) principle.
- For applications, which work with messaging queues.
- Main methods Enqueue and Dequeue
- What will be Dequeued next - method Peek
System.Collection.SortedList
- A collection with key/value pairs, where elements are sorted by
key
- Keys must be comparable:
– No different types (for example string vs int) – Sorted by:
- IComparable – for keys
- IComparer - when creating a sorted list, this is given as parameter
- What will be printed out?
System.Collection.Stack
- LIFO (last-in-first-out) principle:
- Main methods: Push ir Pop
- Peek method – to check value without popping it.
System.Collections.Generic
- MS recommends to use generic collections whenever
possible.
- Most commons ones:
– Dictionary<TKey, TValue> – List<T> – Queue<T> – Stack<T> – SortedList<TKey, TValue>
Dictionary
- Main methods:
Method Description Add Adds pair of key/value Clear Clears all pairs ContainsKey Checks if given key exists ContainsValue Checks if given value exists Remove Removes a pair with given key
Custom collection
Method Description Clear Cleans all elements OnInsert Allows to do specific tasks before inserting value OnRemove Allows to do specific tasks after removing value OnSet Allows to do specific tasks before setting value RemoveAt Removes value at given index
- It is possible to create a collection with your own type.
- Inherits from CollectionBase (no Add, Insert, Sort or Search
methods)
Propery Description Capacity Available size Count Value count InnerList Returns smaller ArrayList-type object, from given interval List IList typed variable, where all collection values are stored
Custom collection
Reflection
- Reflection – mechanism, which allows to analyze code
and read/modify/call specific code parts in runtime.
- Might be used in design patterns, such as Factory
- r Inversion of Control.
- WIKI:
– reflection allows inspection of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at compile time. – It also allows instantiation of new objects and invocation of methods.
Simple example
Type class
- Type:
– Type class is base of Reflection mechanism. – Through this class main info for assembly, module or type is accessed. – Type is... class, interface, array, value type, enum, parameter, generic type, etc.
System.Reflection classes
Property Description Assembly Represents a DLL or EXE file and contains properties for the Assembly name, classes, modules, and other metadata language run-time application. EventInfo Represents an event defined in your class and contains properties such as the event name. FieldInfo Represents a field defined in your class and contains properties such as whether the field is public or private. MemberInfo Abstracts the metadata about a class and can represent an event, a field, and so
- n.
MethodInfo Represents a method defined in your class and can be used to invoke the method. Module The module is a file that composes the assembly. This is usually a DLL or EXE file. ParameterInfo Represents a parameter declaration for a method or a constructor. This allows you to determine the type of parameter, its name, as well as other properties. PropertyInfo Represents a property defined in your class and contains properties such as the property name and type.
Assembly class
- Assembly is compiled code, which is saved as an EXE
- r DLL file.
- Assembly class is used to:
– Load something to memory. – Read metadata. – Create instances for types created in that assmebly.
- Most common attributes – in a few slides.
Type+Assembly: example
Create an object and call a method
Create an object and call a method
Assembly class
Prop/Method Description CodeBase Returns the path for the assembly DefinedTypes Returns a collection of the types defined in this assembly ExportedTypes Returns a collection of the public types defined in this assembly(IEnumerable<TypeInfo>) FullName Returns the name of the assembly GlobalAssembl yCache Returns a boolean value indicating whether the assembly was loaded from the global assembly cache Location Returns the path or UNC (Universal Naming Convention) location of the assembly Modules Returns a collection that contains the modules in this assembly
Assembly class methods
Method Description
CreateInstance(String) Creates an instance of the class by searching the assembly for the class name GetCustomAttributes(Boole an) Returns an array of objects that represent the custom attributes for this assembly GetExecutingAssembly Returns an Assembly object for the currently running program GetExportedTypes Returns the public classes defined in this assembly GetModule Returns the specified module in this assembly GetModules() Returns all the modules that are part of this assembly GetName() Returns the AssemblyName for this assembly GetReferencedAssemblies Returns an array of AssemblyName objects that represent all referenced assemblies GetTypes Returns an array of Type object defined in this assembly Load(String) Loads an assembly LoadFile(String) LoadFrom(String)
In practice..
- To reach attributes
- To reach types in one assembly.
- Late binding, accessing methods for types, which were
created later.
- Practical examples:
– Transforming different
- bjects
into standard structure without creating specific mappers. – Creating testing framework (call all methods dynamically). – Etc.
Practical example
Practical example
Factory pattern
- One of the most common
- A lot of implementations (not part of gang-of-four)
- Used as a base for Factory Method and Abstract Factory .
- Creational design pattern:
– Creates objects without disclosing the logic to client. – Newly created objects are accessed through common interface.
- Mostly:
– The object to be created is defined by parameters passed. – An abstraction is returned – interface, abstract class, etc. – Factory creates specific instance.
- Demo – look FactoryDemo.zip
Detour: Call stack
dynamic
- Simmilar to reflection allows dynamic call.
- dynamic can mark variable, field or parameter.
- „In the statically typed world, dynamic gives developers a lot of
rope to hang themselves with“ (@random internet guy)
- If types can be known on compile time, dynamic
should be avoided (same as reflection). Because speed.
- dynamic is compiled to code, which uses reflection
most of the time.
Example
- Pro: any type can be
assigned
- Con: any type can
be assigned.
dynamic
- Minuses:
– No extension methods.
- LINQ usage limited, then.
– Slow.
- When is it OK?
– For example when third party nasty libs are used, and there is
- nly one nice way – dynamic.
– When a lot of casting happens (anyway) – Factory and similar.
dyncamic vs var
Var Dynamic C# 3.0 C# 4.0 Type defered on compile time Type defined on runtime Needs assignment (e.g. var demo; will not work). Does not need assignment (dyncamic demo; will work) Type after initialization can be changed only in "usual" methods: cast, etc. Type can be changed in any ways. Has intelisense help Does not have Intelisense help
Dynamic vs var vs object
- Var: type defined instantly.
- Object: boxing/unboxing dilema (conversions).
- Dynamic: type „found“ after compile time.
- MSDN: dynamic is compiled to objects. Dynamic type
exists only till compile time.
dynamic vs reflection
- Might be used together:
- Main differences:
Reflection Dynamic Check metadata Yes No Call public member Yes Yes Call private member Yes No Static class Yes No
Attributes
- Attributes extends classes, structs (and other types), methods, properties, etc.
- Info to be declared (metadata) is allowed to be added there.
- Can be reached in both – compile and runtime.
- Since atrributes can be read in runtime (thanks to reflection), "owners" of
those attributes can have their behaviour changed on runtime as well (reflection). [attribute(positional_parameters, name_parameter = value, ...)] element
- Positional params show mandatory information.
- Named params show optional information.
Attributes: few notes
- Owner can have many attributes
- System.Attribute is an abstract class, all others
inherit from it.
- Attributes are:
– Defined: Flags, Serializable, Obsolete, Conditional, ir etc. – Custom
Common attributes
Common attributes
Literature
Base (MCSD toolkit):
- 4. Manipulating with strings
- 4. Formating values
- 11. Input validation -> Validating data
- 9. Working with data collections
- 10. Understanding query expressions -> Filtering
Extra (MSDN):
- Regular Expression Language - Quick Reference
- Regular Expression Options
Next lecture
- Most likely:
– LINQ/PLINQ, – Intro to MSSQL – Intro to ORM – Project management:
- Introduction to theory
- Intro to agile (guest)
- How does it look in reality (guest)