Segna il video come già completato  
Se vuoi, sarebbe utile un giudizio su questo video    
In questo video vedremo con utilizzare nuovi metodi TryParse e TryParseExact() nella versione due di Visual Studio 2010 sono stati estesi anche alla classe Guid. Infatti senza questi metodi di controllo il processo di validazione di un Guid presupponeva l'utilizzo di codice diciamo "artigianale". Ad esempio si poteva pensare di intercettare l'eccezione che si verifica nel tentativo di convertire una stringa in un identificativo numerico. Quindi ad esempio creare una funzione ad hoc quindi ad esempio creare una funzione ad hoc ad esempio questa funzione CheckGuid che è richiamata passandogli la stringa del Guid da convertire e tenterà di effettuare appunto la conversione, creando un nuovo guid. Nel caso di successo ritorna la true, in caso di insuccesso ritornerà false. Intercettando l'eccezione che si verifica seguito dell'errore di conversione per cui se facciamo una prova veloce possiamo richiamare questa funzione CheckGuid, passandogli una stringa invalida e lanciando questo codice. Possiamo verificare, magari mettiamo un punto d'interruzione per verificare quale sia il flusso del codice. Il metodo è stato richiamato, andiamo avanti passo per passo questo è il tentativo di conversione della stringa in un nuovo guid. Si verifica l'errore, viene ritornato false per cui possono lasciar andare. Adesso nel codice viene ritornato false. Questo però presuppone il fatto di far generare un'eccezione in un altro metodo sempre per verificare la validità di un guid potrebbe essere l'utilizzo di un'espressione regolare. per cui possiamo sostituire la nostra funzione CheckGuid con un'altra checkguid che in realtà usa un'espressione regolare. Possiamo provare anche in questo caso a lanciare questo codice e sapere passo per passo il flusso. Andiamo avanti, in questo momento si verifica il tentativo di lanciare nell'area della nostra stringa con l'espressione regolare, andiamo avanti, ecco che anche in questo caso il risultato è un bel false. Con Visual studio 20010 fortunatamente è stato introdotto un metodo TryParse(). Come abbiamo detto all'inizio di questo video il metodo TryParse() di Visual Studio 2010 permette di effettuare il tentativo di conversione da stringhe a guid e vedersi ritornato quindi il valore true nel caso di successo e il valore false in caso di errore. Quindi non ci sarà bisogno di me generare alcuna eccezione e quindi trappare l'errore in Visual Studio 2010. Ad esempio creeremo un metodo che si chiamerà ConvertiGuid che, data una stringa passata come parametro tenterà di convertirla in un guid usando appunto questo nuovo metodo TryParse(). Il metodo è esattamente questo qui. Al metodo ConvertiGuid come abbiamo detto prima viene passata come parametro una stringa chiamata string_in_guid della stringa di ingresso e la stringa che verrà passata al metodo e che servirà per generare un vero proprio guid. auto_guid appunto è il guid risultante dalla conversione utilizzando il metodo TryParse(). Questa riga di codice e non fa altro che stampare video il guid di ingresso. Questo è il vero cuore di questo metodo in quanto è il metodo TryParse: prende come parametro la stringa del guid da convertire, e come parametro di uscita il guid risultante. In caso di successo , cioè se Guid.TryParse con questi parametri è uguale a true, allora il programma entrerà in questa riga di codice e ci farà vedere il guid risultante. In caso contrario verrà visualizzata invece una una conversione fallita. Nel metodo Main() non facciamo altro che creare e dichiarare un nuovo guid generato casualmente sul momento e poi convertirlo in vari formati ad esempio il formato B, per il primo tentativo di conversione formatta il guidi che viene generato qui formatta questo guidi utilizza il parametro B ciè includendo guid tra parentesi graffe e usando i trattini. Questo secondo tentativo di conversione invece formatta il guidi tra parentesi tonde invece che graffe e utilizza anche questo i trattini. Questa conversione invece non utilizza nè parentesi e nè trattini sarà un blocco di caratteri successivi. Il formato di invece formata da guid senza parentesi ma usando i trattini la X utilizzerà invece formato esadecimale. Tutti questi come possono vedere sono del guid validi espressi però con della formattazione particolare. Possiamo anche fare prova e vedere di passare un guid invalido ad esempio il guid correttamente creato qua sopra ma formato soltanto da Disney i primi 10 carattere per cui una sottostringa e da 1 a 10 e infine un ultimo un guid non dichiaratamente invalido cioè la stringa "ciao". Proviamo a lanciare questo codice e vediamo risultato del primo tentativo di conversione: il formato B che esattamente questo coi trattini e con la parentesi graffa, è riuscito a convertire la stringa in guid. Se premiamo un tasto viene effettuata la seconda conversione cioè la conversione con nella formattazione con parentesi tonde e trattini. Anche la seconda conversione è riuscita. Premiamo un tasto e andiamo avanti fino alla terza conversione nel formato costituito da un unico blocco. Anche in questo caso la conversione andata bene. La quarta conversione è senza parentesi ma con i trattini, e anche qua siamo andati bene. Formato esadecimale, quello quindi con la X. Anche in questo caso conversione riuscita. Andiamo avanti troveremo la conversione della stringa del guid invalido. Effettivamente si può verificare che la conversione è fallita, a maggior ragione l'ultima conversione cioè quella della stringa "ciao", fallisce anche questa. Quindi tutto questo l'abbiamo fatto con il metodo TryParse che converte in guid indipendentemente dal formato di guid che si passa come parametro. Diverso è il caso invece del metodo TryPrarseExact che invece tenta di convertire una stringa in un guid secondo formato ben preciso. Infatti in un esempio che faremo di seguito tenteremo di convertire il guidi dell'esempio precedente di cui ognuno rappresenta un diverso formato di guid, in formato specifico. Per cui sostituiamo questo blocco di codice con il nuovo e verifichiamo che effettivamente tutta questa prima parte sia uguale. Anche il metodo convertiGuid è identico. L'unica modifica è quella che abbiamo cambiato è il metodo TryParseExact, che oltre alla stringa di input e il guid di output ha un parametro aggiuntivo che definisce quale il formato del guid sta verificarndo. Cioè la conversione avrà effetto soltanto se verrà passato una stringa che rappresenta un guid espresso nel formato che indichiamo con questa lettera. Verifichiamo come abbiamo fatto in precedenza la conversione di queste stringhe nel guid risultante. Lanciamo quindi il codice entriamo nel risultato della prima conversione del primo tentativo di conversione. Viene utilizzato un formato B, tra parentesi graffe e trattini, ma come vediamo il formato B. è differente rispetto al formato N. ricordiamoci formato N. è questo qui cioè un guid formattato senza parentesi e senza trattini: era un blocco di caratteri tutti attaccati tra loro. Per cui non rispecchiando il formato desiderato la conversione fallisce. Proviamo con il secondo formato P, ossia parentesi tonde e trattini. Anche in questo caso il formato non rispecchia il formato corretto per cui fallisce il terzo tentativo di conversione. Invece quello che dovrebbe andare a buon fine perché passa un guid formattato come parametro N. vediamo un po' ed effettivamente la conversione è riuscita. Andiamo avanti il formato D senza parentesi ma con i trattini è fallito il formato X, in esadecimale fallisce anche questo. I guid invalidi sicuramente falliranno, proprio perché la conversione in quel caso è assolutamente impossibile per cui abbiamo visto che mentre il metodo e TryParse() permette la conversione indipendentemente dal formato il metodo invece TryParseExact() è attento al formato che viene passato ed effettua la conversione soltanto se il formato della stringa che si vuole convertire coincide con il formato indicato parametro del metodo cioè esattamente il secondo parametro.
In this video we will use with new methods and TryParse TryParseExact () in the two versions of Visual Studio 2010 have been extended to the Guid class. For without these methods of testing the process of validation of a guide assumes the use of code we say "handmade". For example we could think to catch the exception that occurs in an attempt to convert a string into a numeric identifier. So for example, create a function such as ad hoc and then create an ad hoc function such CheckGuid that this function is called passing the string Guid be converted, and just try to make the conversion, creating a new guid. If successful returns true, return false on failure. Catch the exception that occurs after conversion error so if we do a quick test CheckGuid we can call this function, passing an invalid string and throwing this code. We can check, maybe put a breakpoint to check what is the flow of the code. The method has been called up, we go step by step this is an attempt to convert the string to a new guid. The error occurs, false is returned so they can let go. Now the code is returned false. But this assumes the fact to throw an exception in another way ever to check the validity of a guide may be the use of regular expressions. so we can replace our function with another CheckGuid checkguid that actually uses regular expressions. We can try again to launch this code and know step by step flow. Come on, now occurs in the attempt to launch our string with the regular expression, go ahead, here is that even in this case the result is a nice false. Fortunately, with Visual Studio 20010 was introduced TryParse (). As we said at the beginning of this video the TryParse () Visual Studio 2010 allows you to make the attempt to convert from string to guid and then come back and see a true value if successful and false if an error occurs. So there will be no need for me to generate any exception, and then Trappist error in Visual Studio 2010. For example we will create a method that will be called ConvertiGuid that, given a string passed as parameter will attempt to convert a guid just using this new method TryParse (). The method is exactly that here. The method ConvertiGuid as we have said before is passed as a string parameter called string_in_guid input string and the string that is passed to the method will be used to generate a true right guid. auto_guid exactly is the guid from the conversion using the TryParse (). This line of code does is print the video entry guide. This is the true heart of this method because it is the TryParse: it takes as a parameter the string of the GUID to be converted, and as an output parameter the resulting guid. If successful, that is if Guid.TryParse with these parameters is equal to true, then the program goes into this line of code and we will see the resulting guid. Otherwise it will be displayed instead of a conversion failure. In the Main () method we are doing is creating a new guid and declare randomly generated on the fly and then convert it to various formats such as the B format, the first attempt to convert the format guide that is raised here this guide uses the format parameter B guid species including braces and using dashes. This second conversion attempt but the drive formatted in parentheses instead of braces and also uses this hyphens. This conversion however does not use any parentheses and dashes will be neither a block of subsequent characters. The format consists instead of driving without using hyphens, parentheses, but instead will use the X hexadecimal. All these can be seen as a valid driver's are expressed, however, with the formatting. We can also pass a test and see for example invalid guid the guid correctly set up here but formed only by the top 10 Disney character in a substring, and 1 to 10 and finally a last a GUID that is not declared invalid string " hello ". Try running this code and see the result of the first attempt of conversion: the B that exactly this format with dashes and with the brace, was able to convert the string to guid. If you press a button the second conversion is done with the "conversion" in the formatting with parentheses and dashes. The second conversion was successful. We press a button and move on to the third conversion in the format consists of a single block. Again the conversion went well. The fourth is conversion without parentheses but with hyphens, and even here we did well. Hexadecimal format, so that with the X. Again the conversion failed. Let's find out the conversion of the string of guid invalid. Indeed we can verify that the conversion failed, the more so that the final conversion of the string "hello", this also fails. So we did all this with the method that converts TryParse guid guid regardless of the format of which is passed as parameter. Unlike the case instead of the method TryPrarseExact instead try to convert a string to a second format guid precise. In fact, in an example below we will try to convert the drive from the previous of which each represents a different form of driving, specific format. So we replace this block of code with the new and verify that indeed throughout this first part is equal. The method is identical convertiGuid. The only change is that we have changed is the method TryParseExact, which in addition to the input string and the GUID of output has an additional parameter that defines the format of which is guid verificarndo. That is, the conversion will take effect only if it is passed a string that represents a GUID in the format denoted by the letter. We check as we did before the conversion of these strings in the resulting guid. We launch the code and then enter the result of the first conversion of the first conversion attempt. It uses a format B, braces and hyphens, but as we see the format B. is different from the format N. remember size N. here that this is a guid formatted without dashes and without brackets: it was a block of characters all stick together. So do not reflect the desired format conversion fails. Let's try the second format p, parentheses and dashes. Again the format does not reflect the correct format for which conversion fails the third attempt. Instead what should be successful because it passes a guid formatted as a parameter N. let 'and actually the conversion succeeded. Let's go on the format D but without parentheses with dashes failed the X format, in hexadecimal still does. The guid invalid surely fail, because the conversion in that case it is absolutely impossible that we have seen that while the method and TryParse () allows regardless of format conversion method instead TryParseExact () is close to the format that is passed and maintains conversion only if the format you want to convert the string matches the format specified method parameter that is exactly the second parameter.