p4api Defines the exception levels available in P4Connection. Exceptions will only be thrown when Perforce has errors. This is the default exception level. Exceptions will never be thrown when Perforce has errors. Exceptions will be thrown for both Errors and Warnings. Base functionality for P4Recordset and P4UnParsedRecordset. This is a base class for internal use. Do not use directly. Checks the Recordset to determine if errors occured. True if the p4 command returned errors. This is the same as testing Errors.Count. Checks the Recordset to determine if warnings occured. This is the same as testing Warnings.Count. True if the p4 command returned warnings. Gets an array of error messages returned from the Perforce command. These are the error messages that are returned from Perforce. Gets an error messages returned from the Perforce command. Errors are concatanated to one string, seperated by new lines. Gets an array of warning messages returned from the Perforce command. These are the warning messages that are returned from Perforce. Perforce is not always intuitive in how it defines warnings vs. messages. Always test various scenarios to determine whether the output is a warning or message. Array of warnings returned from Perforce. Delegate to handle the OnPrompt event. Sender P4PromptEventArgs Handle Perforce "prompts". Prompts are from commands that ask the user to respond, such as:
  • login
  • passwd
  • resolve (without an -a* switch)
  • A connection to a Perforce server instance.

    The P4Connection class is the main player in P4.Net. This represents a connection to the Perforce server. Every utility that uses P4.Net will have some variation of the following code:

    P4Connection p4 = new P4Connection(); p4.Connect(); // Run some commands p4.Disconnect();

    Rule number 1: Always remember to disconnect. This frees unmanaged memory, and cleanly disconnects from the Perforce server. P4Connection implements IDisposable, and the Dispose and Disconnect methods can be used interchangeably.

    P4.Net is based off the command-line syntax (as are most other Perforce APIs). Almost all of the commands you issue in P4.Net will use the same arguments as the p4 client executable. For example, say you need to find the latest submitted changelist under a given path (//depot/path).

    From the command line: c:\> p4 changes -m1 -s submitted //depot/path/... From P4.Net: P4Connect p4 = new P4Connection(); p4.Connect(); P4Recordset changes = p4.Run("changes", "-m1", "-s", "submitted", "//depot/path/..."); p4.Disconnect();

    If you don’t know what all the arguments for p4 changes mean, then p4 help changes is your best friend. The first step in building anything with P4.Net, is to know the exact command lines you’d run manually.

    Initializes a new instance of the class. Converts Perforce date (integer) to .Net DateTime. The Perforce API returns most dates as an integer representing the number of seconds since 1/1/1970 in UTC. The command line client generally returns dates as strings in the Perforce server's time zone. The ConvertDate methods use the client's time zone for the offset. DateTime in .Net format. Converts Perforce date (integer value as a string) to .Net DateTime. The Perforce API returns most dates as an integer representing the number of seconds since 1/1/1970 in UTC. The command line client generally returns dates as strings in the Perforce server's time zone. The ConvertDate methods use the client's time zone for the offset. Converts .Net DateTime to Perforce date (integer). The Perforce API returns most dates as an integer representing the number of seconds since 1/1/1970 in UTC. The command line client generally returns dates as strings in the Perforce server's time zone. The ConvertDate methods use the client's time zone for the offset. Checks the case-sensitivity of the Perforce server. True when the connected server is case-sensitive. This must be called after connecting to the server. Connect to the Perforce server Disconnect from the Perforce Server Login to the Perforce Server The password. Creates a new pending changelist. The description. P4PendingChangelist object representing the named pending changelist Determines if the Perforce connection is valid. if set to true it will check if the user is logged in. if set to true it will verify the client exists. true if the connection is valid; otherwise, false. IsValidConnection performs the following 3 checks (depending on the arguments passed).
  • Runs p4 info, and verifies the server is valid.
  • If checkClient is true, verifies that p4 info returns a clientName that is not "*unknown*.
  • If checkLogin is true, verifies that p4 login -s does not have errors.
  • Executes a Perforce command in tagged mode. The command. The arguments to the Perforce command. Remember to use a dash (-) in front of all switches A P4Recordset containing the results of the command. Executes a Perforce command in non-tagged mode. The command. The args. Parse the raw text of a Perforce form into a P4Form object The form command. Raw contents of the form spec. A P4Form object. The fields of the form can be read or updated. If you update a filed, you can save it with Save_Form. Forms are the things that pop-up in an editor when run from a command line. In P4.Net (and most other Perforce APIs), you do not need to parse/format the text manually. Instead, you can get/set the fields using the Fields and ArrayFields collections.

    The following is a list of common form commands:

  • client
  • branch
  • label
  • job
  • user
  • group
  • protect
  • triggers
  • branch
  • When fetching or saving a form, do not use the '-o' and '-i' flags. P4.Net will automatically include them.

    Fetch a form object from Perforce. The form command. The args. A Form object. The fields of the form can be read or updated. If you update a filed, you can save it with Save_Form. Forms are the things that pop-up in an editor when run from a command line. In P4.Net (and most other Perforce APIs), you do not need to parse/format the text manually. Instead, you can get/set the fields using the Fields and ArrayFields collections.

    The following is a list of common form commands:

  • client
  • branch
  • label
  • job
  • user
  • group
  • protect
  • triggers
  • branch
  • When fetching or saving a form, do not use the '-o' and '-i' flags. P4.Net will automatically include them.

    Saves the form to Perforce. The P4Form object retrieved from Fetch_Form. Forms are the things that pop-up in an editor when run from a command line. In P4.Net (and most other Perforce APIs), you do not need to parse/format the text manually. Instead, you can get/set the fields using the Fields and ArrayFields collections.

    The following is a list of common form commands:

  • client
  • branch
  • label
  • job
  • user
  • group
  • protect
  • triggers
  • branch
  • When fetching or saving a form, do not use the '-o' and '-i' flags. P4.Net will automatically include them.

    P4UnParsedRecordSet. Output can be parsed to verify the form was processed correctly.
    Saves the form to Perforce. The form command to run. The formatted spec. P4UnParsedRecordSet. Output can be parsed to verify the form was processed correctly. Saves the form to Perforce. The form command to run. The formatted spec. True to pass the '-f' flag when saving. P4UnParsedRecordSet. Output can be parsed to verify the form was processed correctly. Saves the form to Perforce. The P4Form object retrieved from Fetch_Form. True to pass the '-f' flag when saving. Forms are the things that pop-up in an editor when run from a command line. In P4.Net (and most other Perforce APIs), you do not need to parse/format the text manually. Instead, you can get/set the fields using the Fields and ArrayFields collections.

    The following is a list of common form commands:

  • client
  • branch
  • label
  • job
  • user
  • group
  • protect
  • triggers
  • branch
  • When fetching or saving a form, do not use the '-o' and '-i' flags. P4.Net will automatically include them.

    P4UnParsedRecordSet. Output can be parsed to verify the form was processed correctly.
    Print the contents of a file in Perforce to a byte array. Perforce path to the file. Contents of the file. Text files will be encoded with ANSI encodinge. Unicode files will be encoded as UTF-8 (regardless of P4CHARSET setting). Print the contents of a file in Perforce to a string. Perforce path to the file. Contents of the file. Attempting to call PrintText on a binary file will likely cause corruption.
    If a file is does not exist, a FileNotFound exception will be thrown (regardless of the ExceptionLevel setting).
    Depot Path, Client Path or Local Path can generally be used for the argument depotPath (so long as the argument is valid for the p4 print command line.
    Prints the contents of a Perforce file to a Stream. Writable stream to write the contents to. Perforce path of the file to print. Text encoding of the Stream. If a file is does not exist, a FileNotFound exception will be thrown (regardless of the ExceptionLevel setting).
    Depot Path, Client Path or Local Path can generally be used for the argument depotPath (so long as the argument is valid for the p4 print command line.
    Encoding will only be applied to files with a Perforce type of 'text' or 'unicode'.
    The stream argument can be any valid stream, so long as it is initialized and writable.
    Prints the contents of a Perforce file to a Stream. Writable stream to write the contents to. Perforce path of the file to print. If a file is does not exist, a FileNotFound exception will be thrown (regardless of the ExceptionLevel setting).
    Depot Path, Client Path or Local Path can generally be used for the argument depotPath (so long as the argument is valid for the p4 print command line.
    The stream argument can be any valid stream, so long as it is initialized and writable.
    Runs a print command, and raises events for each file printed. Arguments to the p4 print command. OnPrintStream OnPrintEndFile This method is useful when you need to print several files with a single call to the Perforce server. Calls Disconnect. Raised when Perforce is prompting for a response. Handle Perforce "prompts". Prompts are from commands that ask the user to respond, such as:
  • login
  • passwd
  • resolve (without an -a* switch)
  • The following sample will change the user's password. public class PasswordSetter { private P4Connection _p4 = null; private string _oldPassword = ""; private string _newPassword = ""; PasswordSetter(P4Connection p4) { _p4 = p4; } public void SetPassword(string OldPassword, string NewPassword) { OnPromptEventHandler eh = new OnPromptEventHandler(OnPrompt); _p4.OnPrompt += eh; _oldPassword = OldPassword; _newPassword = NewPassword; //run passwd P4UnParsedRecordSet r = _p4.RunUnParsed("passwd"); //Clear the event just in case _p4.OnPrompt -= eh; //Clear the passwords from memory _newPassword = ""; _oldPassword = ""; } private void OnPrompt(object sender, P4PromptEventArgs e) { switch (e.Message) { case ("Enter old password: "): e.Response = _oldPassword; break; case ("Enter new password: "): e.Response = _newPassword; break; case ("Re-enter new password: "): e.Response = _newPassword; break; } } }
    Raised from P4PrintStreamEvents before a file is printed. Handle this event to initialize a stream that P4API will write to. Raised from P4PrintStreamEvents after a file is printed. Use this event to close any streams that were created by the OnPrintStreamEventHandler event. Gets/Sets a value that overrides the defined MaxScanRows. Servers may set a limit for MaxScanRows for certain users. Set this value to override. A value of 0 indicates no override. Overrides the MaxScanRows defined at the server. Gets/Sets a value that overrides the defined MaxLockTime. Servers may set a limit for MaxLockTime for certain users. Set this value to override. A value of 0 indicates no override. Overrides the MaxLockTime defined at the server. Gets/Sets a value that overrides the defined MaxResults. Servers may set a limit for MaxResults for certain users. Set this value to override. A value of 0 indicates no override. Overrides the MaxResults defined at the server. Gets/Sets the Host-name of the client. Forcing the Host to a different name is useful when using a client that was defined on a different host. Of course, that can cause issues with the client's have list, so use with caution. The client Host name. Gets/Sets the Perforce Server port. The port. Defaults to the value set in your Perforce environment. Port can not be changed after running Connect (not even after a Disconnect). To connect to a server on another port, create a new instance of P4Connection. Gets/Sets the User login used to connect to Perforce. The user. Defaults to the value set in your Perforce environment. After you've set User, you can unset (revert to the default) by setting to User to null. Gets/Sets the client character set. Defaults to the value set in your Perforce environment. After you've set Charset, you can unset (revert to the default) by setting to Charset to null. The client's charset. Get/Sets the name of the calling program. This value is seen in p4 monitor and in the server log files. Defaults to "P4.Net API". Gets/Sets the version of the calling program's version. This value is seen in p4 monitor and the server log files. Defaults to the assembly version of the P4API.dll. Sets the password to conenct with. Do not set the literal password with a server running security level 2 or higher. For those servers, Use the Login method and/or a ticket in place of the Password. The user's password. Sets the ticket file used for Authentication. Use this to override the default location of the TicketFile. Overrided the ticket file location. Gets/Sets the client workspace. Many Perforce commands require a valid client spec to be set in order to run. Defaults to the value set in your Perforce environment. After you've set Client, you can unset (revert to the default) by setting to Client to null. The client name. Gets/Sets the current working directory. Setting CWD can be used so that relative paths are specified. Keep in mind that changing the CWD also might cause P4CONFIG settings to change. The current working directory for the Perforce connection. Sets the client API protocol level. Sets the API compatibility level desired. This is useful when writing scripts using Perforce commands that do not yet support tagged output. In these cases, upgrading to a later server that supports tagged output for the commands in question can break your script. Using this method allows you to lock your script to the output format of an older Perforce release and facilitate seamless upgrades. Note that this method must be called prior to calling Connect.
    See the http://kb.perforce.com/P4dServerReference/ProtocolLevels/PerforceClientLevels for the API integer levels that correspond to each Perforce release.
    The Perforce API level.
    Gets/Sets the Exception level when running Perforce commands. This property controls when P4.Net will throw exceptions when the underlying Perforce commands raise errors and warnings. The default is The exception level for the connection. Checks the server level (version) of the Perforce server. The server's version level. See http://kb.perforce.com/P4dServerReference/ProtocolLevels/PerforceServerLevels for more informantion. The server's version level. Represents a Perforce 'Form' object. Forms are the things that pop-up in an editor when run from a command line. In P4.Net (and most other Perforce APIs), you do not need to parse/format the text manually. Instead, you can get/set the fields using the Fields and ArrayFields collections.

    The following is a list of common form commands:

  • client
  • branch
  • label
  • job
  • user
  • group
  • protect
  • triggers
  • branch
  • When fetching or saving a form, do not use the '-o' and '-i' flags. P4.Net will automatically include them.

    The following example updates the current client. It changes the client root, and adds a line to the view. P4Connection p4 = new P4Connection(); p4.Connect(); P4Form MyClient = p4.Fetch_Form("client"); //Change the root and properties MyClient["Root"] = @"C:\p4\P4.NetClient"; MyClient["Description"] = "Created from P4.Net!"; //Fetch the clientName (for use later in building the view spec). string clientName = MyClient["Client"]; // Build a new array, that has one more element than the current view string[] NewView = new string[MyClient.ArrayFields["View"].Length + 1]; // Copy the existing view lines to the new array MyClient.ArrayFields["View"].CopyTo(NewView,0); // Set the new view line NewView[NewView.Length - 1] = string.Format("//depot/newpath/... //{0}/newpath/...", clientName); MyClient.ArrayFields["View"] = NewView; // Save the form P4UnParsedRecordSet MyResult = p4.Save_Form(MyClient); p4.Disconnect();
    P4Record is a dictionary-like object that provides a means of interpreting Perforce results. The Perforce api provides "parsed" output in the form of key-value pairs. Keys are always strings (case sensitive). From the raw api, the values come in 3 flavors:
  • Simple strings.
  • List of strings.
  • Sparse multi-demensional list of strings.
  • P4.Net does not yet handle the third type (which only comes from certain output of p4 filelog). To access simple string values by key, use the Fields property (or the default indexer). To access lists of strings by key, use the ArrayFields property.
    Gets the FieldDictionary returned from the Perforce command. The single-value fields returned for the current record. Gets the ArrayFieldDictionary returned from the Perforce command. The array-value fields returned for the current record. Returns the value of of the Field by key. This is the same as Fields[key]. The key for String value for the associated key. The value for field 'key'. Parses a Perforce form without making a server connection. The command that would otherwise be used to fetch the form. The Perforce 'specdef' for the form. The raw formated form text. Server encoding (either ANSI or UFT-8). A Perforce form object. LoadFromSpec can be used to parse a form without making a call to the server. LoadFromSpec can be useful in form triggers. It does require you to know the SpecDef to call, which can change when upgrading or changing the server configuration. Formats the P4Form as a formated Perforce spec. String of the formated form spec. Copies the P4Form object into a new instance. A copy of the P4Form object. Gets the form command. The command that was executed when the form was run. Gets a StringCollection containing the names of all the allowable fields in the form. The fields returned by PermittedFields are not necessarily included in Fields.Keys or ArrayFields.Keys. Perforce forms usually do not have keys for empty values. StringCollection containing the names of all the allowable fields in the form. The underlying C++ API 'specdef' defining the form. The C++ 'specdef' that defines the format of the spec. The SpecDef is a formatted string that Perforce uses internally to parse forms. SpecDefs will vary by form, server version, and even with specific server configurations. In general, you should avoid using a SpecDef directly; however, in some cases you can avoid a server call by using the SpecDef. Represents a pending changelist from Perforce. The P4PendindingChangelist object is used to submit files with P4.Net. The first step is to create a new pending changelist, then add the switches "-c", and "1234" (1234 is the changelist number) to all commands that are opening files. In P4.Net, there’s no straight-forward way to submit the default pending changelist. This is by design. If the client workspace has opened files in the default changelist before any P4.Net automation runs, those files will "come along for the ride" when you submit the default changelist. If the user has a JobView set, all jobs in that JobView will automatically be fixed when you submit the default changelist. Both of those behaviors are almost never desired, and I’ve found many scripts that have those bugs. The following example demonstrates submiting files with P4PendingChangelist. P4Connection p4 = new P4Connection(); p4.Connect(); P4PendingChangelist cl = p4.CreatePendingChangelist("My New Changelist\nVery, Very bad description!\nShame on me!"); p4.Run("edit", "-c", cl.Number.ToString(), "//depot/path/foo.cs", "//depot/path/bar.cs"); // Do something to manipulate the files cl.Submit(); p4.Disconnect(); Submits the pending changelist to Perforce. P4UnParsedRecordSet with the results of the submit. Gets the pending changelist's number. The changelist number. Gets the pending changelist's description. The description. Delegate to handle the OnPrintStream event. Arguments describing the printed file. The stream to write the file. Delaget to handle the OnPrintEndFile event. Arguments describing the printed file. The stream that was written. EventArgs class to supply file details. The Perforce depot path to the file being printed. The depot path to the file. Encoding to be used for files with a Perforce type of 'text'. The encoding for Text Files being printed. Encoding to be used for files with a Perforce type of 'unicode'. The encoding form unicode files being printed. Submit action for the file being printed. The last submit action for the file being printed. The Perforce file type of the file being printed. The Perforce filetype of the file being printed. The timestamp of the file being printed. The timestamp of the file being printed. The Perforce changelist number for the file being printed. The Perforce changelist number for the file being printed. Arguments provided for an OnPrompt event. The message from Perforce. The prompt message from Perforce. The value to respond to Perforce with. The response to the Perforce command. Provides output of a Perforce Command in "tagged" moded. P4Recordset is an enumerable collection of P4Records that supply keyed access to information returned from Perforce. Gets an array of records returned from the Perforce command. Array of P4Records. Gets an array of string messages returned from the Perforce command. Array of informational messages returned from a Perforce command. Gets the record at the specified index. Index of the record to get. P4Record Returns the record at 'Index'. This class represents the "unparsed" output from a Perforce command. In general P4UnParsedRecordSet will return an array of strings which is analagous to a line printed to stdout in p4.exe. Errors and Warnings are stored in the Errors and Warnings properties respectively. Gets array of messages returned from the Perforce command. Array of messages returned from Perforce. Gets message at the specified index. This is the same as running record.Messages[0]; Index of the message. String message Message at 'index'. Base exception for P4API. Gets the error message for the exception. Exception: Attempting to run a command while the Perforce Server is not connected! Gets the error message for the exception. Exception: Changing the port when a server is connected is not allowed! Gets the error message for the exception. Exception: Invalid login credentials. Gets the error message for the exception. Exception: Attempting to set a property that can not be set after the server is connected! Gets the error message for the exception. Exception: You can not use the '-o' and '-i' flags in Fetch_Form and Save_Form. Gets the error message for the exception. Exception: Unable to connect to the Perforce Server! Gets the error message for the exception. Error parsing the form spec. Gets the error message for the exception. Support for diff (without -s* flag) not yet implemented Gets the error message for the exception. Support for merging not yet implemented Gets the error message for the exception. Exception: Error attempting to fetch form. Gets the error message for the exception. Exception: Interactive 'Form' commands are unsupported in P4API. Use the 'Fetch_Form' and 'Save_Form' methods of the P4Connection object. Gets the error message for the exception. Exception: Error running Perforce command! Gets the error message for the exception. Gets the P4UnParsedRecordSet that would have been returned if an exception was not thrown. Exception: Error running Perforce command! Gets the error message for the exception. ClientUser ErrorPause method was called. This in unsupported in P4.Net. If you see this, please let the curator know the steps to reproduce. This should not be reachable code. Gets the error message for the exception. Exception: File not found! Gets the error message for the exception. Exception: Can not write to stream. Gets the error message for the exception. Strongly typed dictionary to represent array-valued fields returned from Perforce commands. The FieldDictionary only contains fields that contain a string array values. Fields that return a single string values are stored in .
    If a value is read from a key that does not exist, an empty array will be returned. If a value is set with a key that does not exist, it will automatically be added. This behavior is to support many Perforce commands that omit a key, rather than supply a default value.
    Clears all elements of the dictionary. Tests if the key exists in the dictionary. The key to test True if the key is defined in the dictionary. Removes elements from the dictionary. The key of the element to remove. Gets all keys contained in the dictionary. Keys in the ArrayFieldDictionary. Gets the number of elements in the dictionary Number of items. Returns the value assocatied to the key. The key to search on. String array value associated to the key. Strongly typed dictionary to represent fields returned from Perforce commands. The FieldDictionary only contains fields that contain a single string value. Fields that return array values are stored in . Clears all elements of the dictionary. Tests if the key exists in the dictionary. The key to test True if the key is defined in the dictionary. Removes elements from the dictionary. The key of the element to remove. Gets all keys contained in the dictionary. Keys in the FieldDictionary Gets the number of elements in the dictionary Count of items. Returns the value assocatied to the key. The key to search on. String value associated to the key.