Windows Programming Using C# Regular Expressions, Files & directories Delegates.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
The Web Warrior Guide to Web Design Technologies
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
ISBN Regular expressions Mastering Regular Expressions by Jeffrey E. F. Friedl –(on reserve.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
28-Jun-15 String and StringBuilder Part I: String.
Scripting Languages Chapter 8 More About Regular Expressions.
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Regular Expressions. String Matching The problem of finding a string that “looks kind of like …” is common  e.g. finding useful delimiters in a file,
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Lecture Set 12 Sequential Files and Structures Part B – Reading and Writing Sequential Files.
Last Updated March 2006 Slide 1 Regular Expressions.
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
VBScript Session 13.
Overview A regular expression defines a search pattern for strings. Regular expressions can be used to search, edit and manipulate text. The pattern defined.
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Module 6 – Generics Module 7 – Regular Expressions.
Satisfy Your Technical Curiosity Regular Expressions Roy Osherove Methodology & Team System Expert Sela Group The.
1 CSC/ECE 517 Fall 2010 Lec. 3 Overview of Eclipse Lectures Lecture 2 “Lecture 0” Lecture 3 1.Overview 2.Installing and Running 3.Building and Running.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaBeans and.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Copyright © Curt Hill Regular Expressions Providing a Search Pattern.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Files Tutor: You will need ….
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Input and Output 23: Input and Output
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Classes, Interfaces and Packages
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
17-Feb-16 String and StringBuilder Part I: String.
Ajay Tripathi Input Output. Ajay Tripathi Input/output (IO) refers to the operations for reading and writing data to streams and files. In the.NET Framework,
An Introduction to Regular Expressions Specifying a Pattern that a String must meet.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
OOP Tirgul 11. What We’ll Be Seeing Today  Regular Expressions Basics  Doing it in Java  Advanced Regular Expressions  Summary 2.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
Regular Expressions Copyright Doug Maxwell (
CS 330 Class 7 Comments on Exam Programming plan for today:
Lecture 9 Shell Programming – Command substitution
I/O Basics.
Files and Streams Lect3 CT1411.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Files & Streams.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Windows Programming Using C# Regular Expressions, Files & directories Delegates

2 Contents Regular Expressions Exceptions Files & Directories Delegates

3 Regular Expressions A regular expression is some text which is designed to match other text You have seen one form of this as the wildcards used to match filenames  Eg. *.exe The regular expressions used by.NET are based on Perl5 regular expressions These are different from the ones used to match file names on the command line

4 Regular Expressions The simplest form of regular expression is one which matches itself  “hello”  This will match the text “hello” In addition to regular characters, regex supports various metacharacters These all have special meanings and instruct the regex to match different strings

5 Any Character The simplest metacharacter is the “.” which will match any single character “a.b” will match  “aab”  “abb”  “acb”  “axb”  Or any other 3 character string beginning with a and ending with b

6 Escape Characters But what if you want to search for a string with a period in it? Then you must escape the special meaning of the period as a metacharacter and restore it to a plain old period Backslash is the escape character  “a\.b” matches the single string “a.b”

7 Multiple Occurrences There are metacharacters to represent multiple occurrences of the character in front of them “a*”  Any number of a’s “ab?c”  “ac” or “abc” “ab+c”  “abc” or “abbc” or … “a.+b”  “a” followed by 1 or more chars and a “b” CharMeaning ?Zero or once *Zero or more +Once or more

8 Specific Occurrences You can also specify a specific number of times a character can occur It has several forms  {3} – exactly 3 occurrences  {3,} – 3 or more occurrences  {3, 8} – between 3 and 8 occurrences “.{3,4}ane” will match  “hexane”  “pentane”  “butane”  “propane”

9 Alternatives Often, you want to match one of several strings This can be done by grouping the options in parentheses and using the | “(iso|cyclo)pentane” matches  “isopentane”  “cyclopentane”

10 Closures At times, you need to match one of a set of characters This can be done by placing the characters in square brackets  “[cbf]at” matches “cat”, “bat” and “fat” Runs of character can use a dash  “[a-z0-9-]” Matches any lower case letter or digit or dash The use of a caret reverses the meaning  “[^a-z]” Matches any character other than a lower-case letter

11 String Ends “^” matches the beginning of the string “$” matches the end of string “abc$”  Matches “abc” only at the end of the string “^abc”  Matches “abc” only at the beginning of the string

12 Special Metacharacters SymbolMeaning \wAny word character (alphanumeric or _) \WAny non-word character \sAny whitespace character (space, tab, newline) \SAny non-whitespace character \dAny digit \DAny non-digit \bAny word boundary character \BAny character not a word boundary

13 Regular Expressions in C# C# provides  System.Text.RegularExpressions.Regex Represents a regular expression Match() -- finds first match Matches() -- finds all matches Split() – Splits into an array of strings Replace – replaces matched text  Match Represents the result of a single regex match  MatchCollection Represents the results of multiple matches  Group Represents the match of multiple expressions

14 Matching Strings To match a regular expression  Regex.Match(string input) This returns a Match instance with  Value – the matched substring  Index – where the match occurred  Length – the length of the match  Success – true if anything was matched To find the next match  Match.MatchNext() * see RegexDemo

15 Matching Strings string input = "propane butane hexane septane heptane decane"; string expr ="h.{2,3}ane"; Regex rx = new Regex(expr); Match m = rx.Match(input); while(m.Success) { Console.WriteLine("found \"{0}\" of length {1} at position {2}", m.Value, m.Length, m.Index); m = m.NextMatch(); }

16 Splitting Strings The Split method splits a string into an array of strings where the matches are found The matched characters are discarded  string[] Split(string input)

17 Splitting Strings string input = "A cat, a hat and a mouse"; string sepRegex = " |, "; Regex rx = new Regex(sepRegex); string[] words = rx.Split(input); Console.WriteLine("Split Demo\ninput={0}", input); foreach (string s in words) { Console.WriteLine(s); }

18 Replacing Text The Replace method is used to replace all matching text with replacement text  string Regex.Replace(string input) string input = "I was\twalking while”; Regex rx = new string result = rx.Replace(input, " "); Console.WriteLine("Replace Demo\ninput={0}\nresult={1}", input, result);

19 Contents Regular Expressions Exceptions Files & Directories Delegates

20 Exceptions Exceptions are handled in much the same way as in Java C# has a try-catch-finally statement try statement catch statement [finally statement]

21 Exceptions This differs from Java in that you can have a catch without a parameter which will catch every exception Unfortunately, there is no exception to get information from when it is done this way try { // some statements } catch{ // no parameters, so catch all Console.WriteLine(“unknown exception caught”); }

22 The Exception Class System.Exception is the root of all exception classes The constructors are Exception() Exception(string msg) Exception(string msg, Exception cause)

23 The Exception Class The final form of the constructor is used to envelop an exception in another exception This is useful when a system exception is thrown and you want to wrap it in a more meaningful application exception Numerous properties provide access to the contents of the Exception

24 Exception Properties PropertyExplanation DataA read-only property implementing IDictionary. Might contain key/value pairs relating to the exception or might be null. HelpLinkA string containing a URL or other reference. Is read/write. InnerExceptionA nested exception which can be set only by the constructor. MessageA string message explaining the exception. SourceA string which can be get/set to identify the source of the exception. StackTraceA string showing the call path when the exception was thrown.

25 ApplicationException Class Direct subclasses of Exception are thrown only by the system Applications should throw exceptions derived from ApplicationException ApplicationException extends Exception but adds no new members

26 Throwing Exceptions To throw an exception throw new ApplicationException(“broken”); Both Java and C++ allow methods which throw exceptions to declare them C# does not provide a way for a method to declare that an exception is thrown You must consult the documentation to determine if an exception is thrown by a method

27 Custom Exceptions You can create custom exceptions by extending ApplicationException  Provide constructors which call the base class constructors  Add any fields and constructor parameters for your specific exception information  Add properties/methods for the new fields

28 Contents Regular Expressions Exceptions Files & Directories Delegates

29 Files & Directories This section will explore how to work with files and directories We begin with directories  Directory Contains static methods for creating, deleting, moving and listing directories  DirectoryInfo An instance represents a directory Has instance methods for manipulating the directory

30 Directory Class MethodDescription CreateDirectory( )Creates all directories and subdirectories specified by its path parameter. GetCreationTime()Returns and sets the time the specified directory was created. GetDirectories()Gets named directories. GetLogicalDrives()Returns the names of all the logical drives in the form :\. GetFiles()Returns the names of files matching a pattern. GetParent()Returns the parent directory for the specified path. Move()Moves a directory and its contents to a specified path.

31 Directory Class MethodDescription Delete( )Deletes a directory. Exists()Determines if a directory exists. GetFiles()Returns the names of files in a specified directory. GetCurrentDirectory()Returns the path of the current directory. GetLastAccessTime()Returns the last time file was accessed. GetLastWriteTime()Returns the last time file was written.

32 DirectoryInfoClass MethodDescription AttributesInherits from FileSystemInfo; gets or sets the attributes of the current file. CreationTimegets or sets the creation time of the current file. Existstrue if the directory exists. ExtensionThe File Extension FullNamethe full path of the file or directory. NameThe directory name. RootRoot portion of the path. ParentParent Directory

33 DirectoryInfo Class MethodDescription Create()Creates the directory if it does not exist. CreateSubdirectory()Creates a subdirectory. Delete()Deletes the directory. GetDirectories()Returns an array of DirectoryInfo objects. GetFiles()Returns an array of FileInfo objects. MoveTo()Relocates the directory and its contents. Refresh()Refreshes the directory list. * See FileDemo

34 A File Lister string curDirName = Directory.GetCurrentDirectory(); DirectoryInfo curInfo = new DirectoryInfo(curDirName); Console.WriteLine("Listing for {0}", curInfo.FullName); DirectoryInfo[] dlist = curInfo.GetDirectories(); foreach (DirectoryInfo d in dlist) { Console.WriteLine("{0}\t\t{1}", d.Name, d.LastWriteTime); } FileInfo[] flist = curInfo.GetFiles(); foreach (FileInfo f in flist) { Console.WriteLine("{0}\t\t{1}", f.Name, f.LastWriteTime); }

35 Working with Files Two classes are provided to deal with files  File A collection of static methods to manipulate files  FileInfo Instance methods to manipulate a single file These classes are analogous to the two directory classes They add the ability to read and write files

36 Reading and Writing Files Files can be read and written in two ways  Binary Binary data is written to a file Fast, efficient, not human readable Suited for writing data structures  Text Converts bytes to a specific character encoding Slower than binary Can be read by humans

37 Stream Class The Stream class is used to read and write binary data from and to a file Read methods  int Read(byte[] buf, int offset, int count) Reads up to count bytes into buf at offset Return the number of bytes read or zero at EOF  int ReadByte() Reads one byte Returns -1 at EOF

38 Stream Class Write methods  void Write(byte[] buf, int offset, int count)  void WriteByte(byte);  void Flush(); Direct Access Methods  long Seek(long offset, SeekOrigin);

39 SeekOrigin An enumeration with values indicating where a seek should be from  Begin, Current, End Seeking moves the read/write pointer through a file and determines where the next read or write will occur

40 StreamReader Class This reads a file by converting the bytes to characters  int Read() Reads the next char, returns -1 on EOF  int Read(char[] buf, int offset, int count) Reads up to count chars into buf at offset Return 0 at EOF  string ReadLine() Reads the next line Returns null on EOF

41 StreamWriter Class Used to write text files  void Write(char)  void Write(char[])  void Write(string)  Void Flush()

42 Buffered Streams Read and writing a byte at a time is painfully slow It is much more efficient to read and write a buffer full at a time The BufferedStream class does just that It works just like a stream Just wrap it around your stream BufferedStream bs = new BufferedStream(stream);

43 Opening Binary Streams Open one stream for reading and one for writing Use the static methods of the File class  Stream OpenRead(string path);  Stream OpenWrite(string path);

44 Reading and Writing Text Files To create a file for writing StreamWriter sw = new StreamWriter("MyFile.txt"); To open a file for reading FileInfo fi = new FileInfo("MyFile.txt"); StreamReader sr = fi.OpenText();

45 Reading and Writing Text Files The following example  Checks to see if a file exists  If it does not, it opens the file for writing and writes some content  It then opens the file for reading and writes the contents to the console  It then closes the file

46 Read/Write Example if (! File.Exists("MyFile.txt")) { StreamWriter sw = new StreamWriter("MyFile.txt"); sw.WriteLine("Line 1"); sw.WriteLine("Line 2"); sw.WriteLine("Line 3"); sw.Close(); } FileInfo fi = new FileInfo("MyFile.txt"); StreamReader sr = fi.OpenText(); string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } sr.Close(); fi.Delete();

47 Contents Regular Expressions Exceptions Files & Directories Delegates

48 Delegates A delegate is  A single function pointer  A collection of pointer to the same type of function It is simply a variable which can hold one or more pointers to functions In C and C++ these are known as callbacks

49 Delegates In may programming tasks you want to perform an action but want that action to be flexible This means you want the client of your class to provide the action, yet you want to invoke it There are a couple of solutions to this problem

50 The Visitor Pattern You are writing a container class You want clients to be able to perform some action on every element of your container You do not want them to know how your class is implemented So, how do you let them visit every element in a container without knowing how the container is implemented?

51 The Delegate Pattern The delegate pattern says that you want to perform a logical action but leave the implementation to be specified at run-time Therefore, you create a delegate and call it At run-time, the delegate is assigned the value of a real function Thus, when you call the delegate, you actually call the function assigned at run time

52 Implementing the Delegate Pattern A delegate can be used to solve the vistor pattern But how do you implement a delegate?  In C/C++ use a function pointer  In Java use an interface  In C# use the special delegate type

53 The Interface Solution To implement a solution to the visitor pattern using interfaces  First declare an interface public interface Visitor { void Visit(object obj); }  Then create a class which implements the Visitor interface

54 The Interface Solution public class PrintVisitor: Visitor { void Visit(object obj) { Console.WriteLine(obj); }  The final step is to create a container class which will provide a method to visit all of the elements it contains and invoke the visitor

55 The Interface Solution public class MyArray { int[] ar; public MyArray(int sz) { ar = new int[sz]; } public void VisitElements(Visitor v) { foreach(int i in ar) v.Visit(i); }

56 The Interface Solution This just leaves writing the code to bring it all together MyArray ar1 = new MyArray(10); // put something in the array ar1.VisitElements(new PrintVisitor());

57 Now, Back to Delegates C# lets you declare a delegate as something which can be associated with one or more functions with the same signature and return type  public delegate void ArrayVisitor( object o);  This declares a delegate Called ArrayVisitor Which accepts a single object parameter And returns void

58 Creating a Delegate Begin by creating a method with the required signature and return type public void printer(object o) { Console.WriteLine(o); } Then, create a delegate from it ArrayVisitor v1 = new ArrayVisitor(printer);

59 Using a Delegate OK, so now that we have a delegate, how do we use it? object[] ar = new object[5]; // put some values in the array foreach(object obj in ar) v1(obj);

60 Multicast Delegates So far we can invoke one method when we invoke a delegate What if we wanted to be able to do more than what one method could do? We could have a delegate which could invoke several methods when it was invoked! This is called a multicast delegate

61 Multicast Delegates Declare a multicast delegate ArrayVisitor multiVisitor; Now, assign a method to it multiVisitor = new ArrayVisitor(printer); And then add another multiVisitor += new ArrayVisitor(printer1); Now, when multiVisitor is invoked, it will invoke both printer and printer1

62 Multicast Delegates You can add as many delegates as you like to a multicast delegate You can remove a delegate from a multicast delegate by subtracting it ArrayVisitor multiVisitor, v1, v2; v1 = new ArrayVisitor(printer); v2 = new ArrayVisitor(printer1); multiVisitor = v1; multiVisitor += v2; multiVisitor -= v1; * see VisitableArray

63 Event Handling GUI programming is event driven When a button is clicked, an event is generated This event is dispatched to any listeners who have registered an interest in the event This is called the observer pattern or publish and subscribe Delegates are used to implement lists of event handlers in.NET GUI programming