1. How to initialize the VGSecurityRuntime ?

The VGSecurityRuntime is a crucial component of the Visual-Guard .NET API. It provides access to various functionalities of the API, such as user management, role management, and permission management.

To use the VGSecurityRuntime, you first need to add the following namespaces in your code:

using Novalys.VisualGuard.Security; 
using Novalys.VisualGuard.Security.Common; 
using Novalys.VisualGuard.Security.CommonProfileAttribute; 
using Novalys.VisualGuard.Security.Database; 
using Novalys.VisualGuard.Security.Membership; 
using Novalys.VisualGuard.Security.UserProfile;
using System; 
using System.Collections.Generic;

Once these namespaces are included, you can get an instance of the VGSecurityRuntime by calling VGSecurityManager.Runtime:

VGSecurityRuntime runtime = VGSecurityManager.Runtime;

This instance of VGSecurityRuntime can then be used to perform various operations related to user management, role management, and permission management.

2. How to authenticate user ?

  1. Initialize the API: Start by initializing the Visual-Guard API within your .NET application. This involves setting up the necessary references and configuring the API with your application’s specific settings.
  2. User Credentials: Collect the user’s credentials, typically a username and password, through your application’s login interface.
  3. Call the Authentication Method: Use the Visual-Guard API to call the authentication method, passing in the user’s credentials. The API will then process these credentials against the stored user data in the Visual-Guard repository.
  4. Handle the Response: The API will return a response indicating the success or failure of the authentication attempt. Handle this response appropriately within your application, granting access for successful authentications or providing an error message for failures.
  5. Implement Additional Checks: If your application uses Multi-Factor Authentication (MFA) or other security policies, implement these checks following the initial authentication to ensure comprehensive security compliance.

By following these steps, you can securely authenticate users in your .NET applications using the Visual-Guard API, leveraging its robust security framework to protect your application and data.

2.1 How to authenticate a user?

Introduction

In Visual-Guard, user authentication is a crucial step that verifies the identity of a user trying to gain access to an application. The Visual-Guard .NET API provides various methods to authenticate a user, including VisualGuard authentication, Database authentication, Windows authentication, and Windows authentication by credentials.

Authentication

VisualGuard Authentication: This method authenticates a user using a username and password stored in Visual-Guard.

//Authenticate visualGuard user
var authenticationState = runtime.Authenticate("jsmith", "pwd", VGAuthenticationMode.VisualGuard);

Database Authentication: This method authenticates a user using a username and password stored in a database.

var authenticationState = runtime.Authenticate("sa", "pwd", VGAuthenticationMode.Database);

Windows Authentication: This method authenticates the current Windows account.

var authenticationState = runtime.Authenticate("", "", VGAuthenticationMode.Windows);

Windows Authentication by Credentials: This method authenticates a Windows account using domain credentials.

The username needs <Domain>\<username> of your domain

var authenticationState = runtime.Authenticate(@"novalys\jsmith", "pwd", VGAuthenticationMode.WindowsByCredential);

After the authentication attempt, the authenticationState.Status property can be used to check the status of the authentication process. The status can indicate success, failure, or other conditions such as an expired account or a locked account.


How to manage the authentication status?

var authenticationStatus = authenticationState.Status;
if (authenticationStatus.HasFlag(VGAuthenticationStatus.Failure))
{
#region Status is Failure along with other status

if (authenticationStatus.HasFlag(VGAuthenticationStatus.UserAccountNotYetAvailable))
{
    //Status is failure as user account is not yet available
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.UserAccountDisabled))
{
    //status is failure as user account is disabled
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.UserAccountExpired))
{
    //status is failure as user account is expired
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.UserNotAuthorized))
{
    //status is failure as user account is not authorized for access
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.ProcessCanceled))
{
    //Status - failure authentication Process is Canceled
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.UserAccountLocked))
{
    //status is failure as user account is locked out
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.PasswordIsLocked))
{
    //status is failure as user account is locked out
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.NotApproved))
{
    //status is failure as user account is not approved
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.UserNotFoundInCustomStorage))
{
    //status is failure as user account not found in custom storage
}
else if (authenticationStatus.HasFlag(VGAuthenticationStatus.MustChangePasswordAtNextLogon))
{
    #region Case - When Password is expired or password doesn't pass validation, and grace logins are completed
    string message;
    if (authenticationStatus.HasFlag(VGAuthenticationStatus.PasswordExpired))
    {
        //status is failure. User must change his/her password as password is expired
    }
    else if (authenticationStatus.HasFlag(VGAuthenticationStatus.PasswordDoesNotPassValidation))
    {
        //status is failure. User must change his/her password as password does not pass validations as per password policy
    }
    else
    {
        //status is failure. User must change his/her password.
    }
    #endregion
}
else
{
    //write your code here to show authentication is failed
    //User is not authenticated, status is failure due to Invalid username or password


    if (authenticationStatus.HasFlag(VGAuthenticationStatus.LastBadLogin))
    {
        //Last bad login, next bad login will lock this user account
    }
    else if (authenticationStatus.HasFlag(VGAuthenticationStatus.PasswordWillBeLocked))
    {
        //user account is locked
    }
}
#endregion
}
else
{
#region If Status is Success, but along With other status also(password expired or password not pass validation).

if (!authenticationStatus.HasFlag(VGAuthenticationStatus.Success))
{
    if (authenticationStatus.HasFlag(VGAuthenticationStatus.PasswordExpired))
    {
        //status is success but password is expired.
    }
    else if (authenticationStatus.HasFlag(VGAuthenticationStatus.PasswordDoesNotPassValidation))
    {
        //status is success but password does not pass validations of password policy. 
    }
}
else
{
    //status is success -> Successful login -
    //write your code to procceed after successful authentication
}

#endregion
}

2.2 How to authenticate with MFA?

To use VG MFA, you need a VGMFA license.

What is the VGMFAAuthMode?

In Visual-Guard, it has 2 types of MFA authentication:

  • VGMagicLink, that sends a link to the validated user email. When the user clicks, that validates the authentication (Synchro System).
  • VGOTP, that sends to the user validated mobile number. User then enters the OTP and validates the authentication.

What is the VGMFATransportMode?

In Visual-Guard MFA, it has 2 transport mode:

  • SMS, that sends OTP/Link to the user for authentication
  • Email, that sends OTP/Link to the user for authentication

VG 2024.0 Sample

//Create or re-use existing VG Runtime
using (VGSecurityRuntime runtime = new VGSecurityRuntime(VGSecurityManager.Runtime))
{
    //Authenticate the user
    VGAuthenticationRequest request = new VGAuthenticationRequest(new VGNamePasswordCredential("<username>", "<password>"));
    VGAuthenticationResponse response = runtime.Authenticate(request);

    //If user need to enroll for MFA
    if (response.IsMFAEnrollmentRequired)
    {
        //Case: Enroll user's email address. Similary you can enroll mobile number
        var enrollRequest = new VGMFAEnrollmentRequest(request.RequestId, "<Email Address>");
        var enrollResponse = runtime.MFA.SendEmailVerification(enrollRequest);
        if (enrollResponse.Status == VGMFAEnrollmentStatus.Success)
        {
            //OTP received in email
            enrollRequest.SecureCode = "<OTP>";

            //Validate the OTP received in email
            var validResponse = runtime.MFA.ValidateEmail(enrollRequest);
            if (validResponse.Status == VGMFAEnrollmentStatus.Success)
            {
                return;
            }
        }
    }

    //If user need to authenticate with MFA before proceeding
    if (response.IsMFAAuthenticationRequired && null != response.MFAAvailables && 0 < response.MFAAvailables.Count)
    {
        //Select any one available MFA mode for authentication
        VGMFAAvailable selectedMFA = response.MFAAvailables.First();

        VGMFACredentialRequest mfaRequest = new VGMFACredentialRequest(selectedMFA.RequestId, selectedMFA.Id);
        mfaRequest = selectedMFA.GetMFACredential();

        VGAuthenticationRequest mfaAuthRequest = new VGAuthenticationRequest(mfaRequest);
        response = runtime.Authenticate(mfaAuthRequest);

        //In case of OTP mode
        if (response.IsMFAWaitingUserAction)
        {
            string readKey = Console.ReadLine();
            mfaRequest.SetOTP(readKey);

            request = new VGAuthenticationRequest(mfaRequest);
            response = runtime.Authenticate(request);                            
        }

        //Authenticated
        if (response.Status.HasFlag(VGAuthenticationStatus.Success))
        {

        }
    }
}

VG 2020.3 Sample

//Create or re-use existing VG Runtime
using (VGSecurityRuntime runtime = new VGSecurityRuntime(VGSecurityManager.Runtime))
{
    // In this case the VGPrincipal is already load, you want to ask MFA authentification 
    var status = runtime.Authenticate("<username>", "<password>", VGAuthenticationMode.VisualGuard);

    if (!status.IsFailed)
    {
        var auth = runtime.MFAAuthentication(VGMFATransportMode.SMS, VGMFAAuthMode.OTP);

        //MFA mode selected = OTP sent by SMS
        if (auth.IsUserAccountNotYetAvailable)
        {
            //If MFA not yet enabled, then Enable it by program
            runtime.MFA.ActiveMFA(runtime.Principal);
        }

        //The user don't have any any
        if (auth.HasUserAccountMissingEmail)
        {
            Console.WriteLine("Email not yet available ");
            //Set an email address
            runtime.MFA.SetEmail("<Email Address>");
        }

        //The user don't have any mobile phone
        if (auth.HasUserAccountMissingMobilePhone)
        {
            Console.WriteLine("Mobile number not yet available");
            //Set an a mobile number
            runtime.MFA.SetMobilePhone("< +xx Mobile Number>");
        }

        // The user need to provide an OTP 
        if (auth.IsMFAWaitingUserAction)
        {
            Console.WriteLine("Need OTP value:");
            var otp = Console.ReadLine();
            auth = runtime.MFAAuthentication(otp);
        }
    }
    else
    {
        //The status is failed
        if (status.IsMFAEnrollmentRequired)
        {
            if (status is VGAuthenticationResponse)
            {
                var response = (VGAuthenticationResponse)status;
                var mfaRequestId = response.AuthenticationEnrollmentRequest.Id;

                //Can we enroll ?
                var needToUseVGIdentityServerUIMode = false;
                if (needToUseVGIdentityServerUIMode)
                {
                    // Navigate to the url
                    // Browse this url : response.AuthenticationEnrollmentRequest.EnrollmentUrl
                    var nav = response.AuthenticationEnrollmentRequest.EnrollmentUrl;

                }
                else
                {
                    if (response.AuthenticationEnrollmentRequest.TransportModes.Contains(VGMFATransportMode.SMS))
                    {
                        Console.WriteLine("Enter a mobile number ");
                        var mobileNumber = Console.ReadLine();

                        var enrollRequest = new VGMFAEnrollmentRequest(mfaRequestId, mobileNumber);
                        var enrollResponse = runtime.MFA.SendMobileNumberVerification(enrollRequest);
                        if (enrollResponse.Status == VGMFAEnrollmentStatus.Success)
                        {
                            Console.WriteLine("Enter OTP: ");
                            var otp = Console.ReadLine();

                            //OTP received on Mobile number
                            enrollRequest.SecureCode = otp;

                            //Validate the OTP received in email
                            var validResponse = runtime.MFA.ValidateMobileNumber(enrollRequest);
                            if (validResponse.Status == VGMFAEnrollmentStatus.Success)
                            {
                                //User enrolled and need to re-authenticate with the username/password to proceed with the MFA authentication
                                return;
                            }
                        }
                    }
                    else if (response.AuthenticationEnrollmentRequest.TransportModes.Contains(VGMFATransportMode.Email))
                    {
                        Console.WriteLine("Enter an email ");
                        var email = Console.ReadLine();

                        var enrollRequest = new VGMFAEnrollmentRequest(mfaRequestId, email);
                        var enrollResponse = runtime.MFA.SendEmailVerification(enrollRequest);
                        if (enrollResponse.Status == VGMFAEnrollmentStatus.Success)
                        {
                            Console.WriteLine("Enter OTP: ");
                            var otp = Console.ReadLine();

                            //OTP received on email
                            enrollRequest.SecureCode = otp;

                            //Validate the OTP received in email
                            var validResponse = runtime.MFA.ValidateEmail(enrollRequest);
                            if (validResponse.Status == VGMFAEnrollmentStatus.Success)
                            {
                                //User enrolled and need to re-authenticate with the username/password to proceed with the MFA authentication
                                return;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Don't support this mode");
                    }
                }
            }
        }
    }
}

3. How to manage users ?

To use the API of Visual-Guard, you need to meet certain prerequisites:

  1. The VGSecurityRuntime must be initialized.
  2. The user must be authenticated.
  3. The current user needs to have some administration rights.

The VGSecurityRuntime is based on VGSecurityRuntime.<Entity>, where <Entity> can be various components of the system such as Roles, Membership, Permissions, etc. These entities allow you to manage different aspects of the system:

  • VGSecurityRuntime.Roles is used to manage all roles.
  • VGSecurityRuntime.Membership is used to manage the users.
  • VGSecurityRuntime.Permissions is used to manage all permissions.

3.1 How to create a user ?

In Visual-Guard, user management is a key aspect of maintaining secure access to your applications. The Visual-Guard .NET API provides methods to create users in different contexts, including Visual-Guard users, Windows account users, and Database account users.

Here’s a brief overview of each method:

Creating a Visual-Guard User: This method creates a user with a username, password, and other optional information in Visual-Guard.

VGMembershipCreateStatus createStatus; 
VGMembershipUser jsmithUser = runtime.Membership.CreateUser("jsmith", "pwd", "jsmith@xyz.com", string.Empty, string.Empty, true, "user description", "John", "Smith", out createStatus);


//Easy creation of the user
VGMembershipUser tempUser = runtime.Membership.CreateUser(“mytestuser”, “pwd”);

Creating a Windows Account User: This method creates a user using a Windows account in a specified domain.

// Get all domains define your VGRepository
var domains = runtime.Domains.GetAllActiveDirectoryDomains(); 

// Set one domain
var selectedDomain = domains[0]; 

//provide the domain in which the window account need to be created 
//Create windows account 
VGMembershipUser windowUser = runtime.Membership.CreateActiveDirectoryUser(selectedDomain, @”novalys\firstuser”, “pwd”, null,out createStatus);

Creating a Database Account User: This method creates a user using a database account.

VGMembershipCreateStatus createStatus; 
//Create Database account 
VGMembershipUser dbUser= runtime.Membership.AddDBUser(new VGDBUser(“sa”), out createStatus);

After creating a user, the createStatus variable can be used to check the status of the user creation process. The status can indicate success, failure, or other conditions such as a duplicate username or email, too many users, invalid input, etc.


How to manage the creation status ?

if (createStatus == VGMembershipCreateStatus.Success)
{
  //user creation is successful
  //write your code 
}
else
{
  switch (createStatus)
  {
      case VGMembershipCreateStatus.DuplicateUserName:
          //User is not created as username already exists
          break;

      case VGMembershipCreateStatus.DuplicateEmail:
          //User is not created as user with same email address already exist
          break;

      case VGMembershipCreateStatus.TooManyUsers:
          //User is not created as user count has been reached to maximum as per license.
          break;

      case VGMembershipCreateStatus.InvalidComment:
          //User is not created as invalid comments
          break;

      case VGMembershipCreateStatus.InvalidEmail:
          //User is not created due to invalid emailaddress
          break;

      case VGMembershipCreateStatus.InvalidPassword:
          //User is not created due to invalid password
          break;

      case VGMembershipCreateStatus.InvalidQuestion:
          //User is not created due to invalid question                        
          break;

      case VGMembershipCreateStatus.InvalidAnswer:
          //User is not created as invalid answer
          break;


      case VGMembershipCreateStatus.InvalidUserName:
          //User is not created as username is invalid
          break;

      case VGMembershipCreateStatus.InvalidWindowsAccount:
          //User is not created due to invalid window account
          break;

      case VGMembershipCreateStatus.UserRejected:
          //User creation is rejected
          break;

      case VGMembershipCreateStatus.ProviderError:
          //User is not created as there is some issue in identity module
          break;

      default:
          break;

  }
}

3.2 How to change the password ?

In Visual-Guard, maintaining secure and updated user credentials is vital. The Visual-Guard .NET API provides methods to change a user’s password, either by the user themselves or by an administrator.

Here’s a brief overview of each method:

  1. User Changing Their Own Password: A user can change their own password by providing their old password and the new password they want to set.
runtime.Membership.ChangePassword("jsmith", "oldpwd", "newpwd");

Administrator Forcing a Password Change: An administrator can force a password change for a user. To do this, the VGSecurityRuntime.Principal needs to have administrator rights.

// Get the user
var user = runtime.Membership.GetUser("jsmith");

// Reset the password of the user
runtime.Membership.ForcePassword(user, "newpwd");

These methods provide flexibility in managing user credentials, allowing for both user-initiated and administrator-forced password changes.

3.3 What is the principal ?

In Visual-Guard, the “Principal” represents the currently authenticated and authorized user. Once a user is authenticated in runtime, you can access the current principal using runtime.Principal.

The Principal object provides a variety of properties that allow you to access information about the user’s roles, permissions, and groups. Here are some examples:

  • currentPrincipal.Roles: This property provides a list of roles granted to the user for the current application.
  • currentPrincipal.GetAllCurrentPermissions(): This method returns a list of permissions granted to the user for the current application.
  • currentPrincipal.ContextualGroups: This property provides a list of selectable contextual groups.
  • currentPrincipal.GrantedGroups: This property provides a list of groups which are directly assigned to users.
  • currentPrincipal.Groups: This property provides a list of groups which are directly assigned and also their descendant groups.
  • currentPrincipal.ProfileValues: This property gets a list of profile values for the current principal.

You can also change and save profile values for the principal. For example:

// Change profile values for principal
// where attributeId is propertyId of attribute
currentPrincipal.ProfileValues.SetValue(attributeId, 15);
currentPrincipal.ProfileValues.SetValue(attributeId, "HelloWorld");

// Save/update profile values for current principal
currentPrincipal.ProfileValues.Save();

3.4 How to get a users ?

Get Users from VGRepository

//Get all users from the storage sorted by given columns            
int totalrecords;
var allusers= runtime.Membership.GetAllUsers(0, int.MaxValue, Security.Common.VGPrincipalSortByColumnType.LastModificationDate, Security.Common.VGSortOrderType.Descending, out totalrecords);

Find users by user information (ex. email, username, locked, approved, user attributes etc)

//you can find users by various criterias.

//Find users by authentication mode
var findUsers = runtime.Membership.FindUsersByAuthenticationMode(VGAuthenticationMode.Windows);

//Find users by email
findUsers = runtime.Membership.FindUsersByEmail("jsmith@xyz.com");
findUsers = runtime.Membership.FindUsersByEmail("%@novalys.com");

//Find users by firstname, lastname
findUsers = runtime.Membership.FindUsersByFirstName("John");
findUsers = runtime.Membership.FindUsersByLastName("Smith");

//Find users by locked,unlocked, approved, unapproved  
findUsers = runtime.Membership.FindUsersByState(VGMemberShipUserState.IsLocked);
findUsers = runtime.Membership.FindUsersByState(VGMemberShipUserState.IsApprouved);

//Find users by name            
findUsers = runtime.Membership.FindUsersByName("jsmith");

Find users by profile attributes

//various prototypes are available to find users with attribute values.
//attributeId - is the Guid of the attribute which need to be searched

//few examples

//search users for which, this attribute's value is between 15 and 20.
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, 15, 20);

//search users for which, this attribute's value is 15 
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, 15);

//search users for which, this attribute's value is today's Date 
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, DateTime.Now.Date);

//search users for which, this attribute's value is true
findUsers = runtime.Membership.FindUsersByProfileAttributeValue(attributeId, true);

3.5 How to update an user ?

How to update the basic information of the user ?

Update user details (like Firstname,Lastname, email, Description etc)

// Get the membership user
var user = runtime.Membership.GetUser("jsmith");

//Edit user
//you can update the details of the user
user.FirstName = "Johny";
user.Title = "Mr";
user.Comment = "User from IT Team";
user.Email = "modified@xyz.com";

//Lock/Unlock user
user.IsLockedOut = true;

//Approve/Unapprove user
user.IsApproved = false;

//update user details
runtime.Membership.UpdateUser(user);

How to update an user profile ?

Get the value of the profile

// Get the user
var user = runtime.Membership.GetUser("jsmith"); 

// Get the value of the attributes
string companyName = user.GetValue<string>("CompanyName"); 
int age = user.GetValue<int>("Age"); 
DateTime dtBirthDate = user.GetValue<DateTime>("BirthDate");

Update the profile values of the user

// Get the user
var user = runtime.Membership.GetUser("jsmith");

// Set a values
user.SetValue<string>("CompanyName", "Novalys");
user.SetValue<int>("Age", 35);
user.SetValue<DateTime>("BirthDate", DateTime.Now.Date);

// Update the user
runtime.Membership.UpdateUser(user);

3.6 How to delete a user ?

// Get a user 
var tempUser = runtime.Membership.GetUser("tempUser");

//Delete user 
runtime.Membership.DeleteUser(tempUser);

3.7 How to create an user attributes ?

You can create multiple user attributes

The user attributes have a type

  • Integer
  • Boolean
  • Double
  • DateTime
  • Image
  • BinaryData
  • DropDownItems
//you can create user profile attribute for various datatypes

//string
VGProfileAttribute attrCompany= runtime.Profile.CreateProfileAttribute("CompanyName", VGProfileDataType.String, "Company Name", "This attribute represents company name of the user");

//DateTime
VGProfileAttribute attrBirthDate = runtime.Profile.CreateProfileAttribute("BirthDate", VGProfileDataType.DateTime, "BirthDate", "This attribute represents BirthDate of the user");

//Integer
VGProfileAttribute attrAge = runtime.Profile.CreateProfileAttribute("Age", VGProfileDataType.Integer, "Age", "This attribute represents an age of the user", 150, string.Empty, true, false, false, true, 0, "Primary Information", string.Empty, VGAttribute_InformationType.None);

//BinaryData
VGProfileAttribute attrBinaryData = runtime.Profile.CreateBinaryDataProfileAttribute("BinaryData", "BinaryData", "This attribute represents certificate binarydata", null);

//DropDownList
VGProfileAttribute attrDropDown = runtime.Profile.CreateDropDownProfileAttribute("Contry", "Contry", "This attribute represents country of the user", new List<string> { "France", "US", "India", "Canada" },"India");

//Image
VGProfileAttribute attrProfilePic = runtime.Profile.CreateProfileAttribute("ProfilePic", VGProfileDataType.Image, "ProfilePicture", "This attribute represents a profile picture of the user");

4. How to manage group ?

The guide begins by detailing the necessary namespaces to be included in your code. It then explains how to define the Visual Guard runtime, which is a crucial step to perform any operation on VGGroup.

The guide provides detailed instructions on how to create, update, and delete VGGroups. It also explains how to create group profile attributes and how to get and set group profile values.

The guide further provides information on how to retrieve all groups from the VGRepository based on the rights of the user. It also explains how to find groups by various parameters such as group name pattern or profile attribute.


Add following namespaces in your code

using Novalys.VisualGuard.Security;
using Novalys.VisualGuard.Security.Common;
using Novalys.VisualGuard.Security.CommonProfileAttribute;
using Novalys.VisualGuard.Security.Database;
using Novalys.VisualGuard.Security.Membership;
using Novalys.VisualGuard.Security.UserProfile;
using System; 
using System.Collections.Generic;

Define VisualGuard runtime

VGSecurityRuntime runtime = VGSecurityManager.Runtime;

How to Create/Update/Delete VGGroup

//Create/Update/Delete Group 
//create group 
VGGroup groupHR = runtime.Groups.CreateGroup("HR Department", "This group represents a HR Division", null); 

//create group under specific group 
VGGroup groupHRBranchA = runtime.Groups.CreateGroup("HR Department- Branch A", groupHR); 
VGGroup groupHRBranchB = runtime.Groups.CreateGroup("HR Department- Branch B", groupHR); 
VGGroup groupHRBranchC = runtime.Groups.CreateGroup("HR Department- Branch C", groupHR); 

//update group 
groupHR.Description = "HR Division"; groupHR.Data1 = "Data1 - You can store any important information here"; 

groupHR.Data2 = "Data2 - You can store any important information here";
groupHR.Data3 = "Data3 - You can store any important information here"; 
groupHR.Name = "HR Dept"; runtime.Groups.UpdateGroup(groupHR); 

//delete group 
runtime.Groups.DeleteGroup(groupHRBranchC);

Create group profile attributes

//Create group profile attributes
var attrBranchCode = runtime.Groups.CreateProfileAttribute("BranchCode",VGCommonProfileDataType.String, "BranchCode", "This attribute represents a branch code");
var attrBranchActive = runtime.Groups.CreateProfileAttribute("IsBranchActive", VGCommonProfileDataType.Boolean, "IsActive", "This attribute represents if branch is active");


var profileAttribteDef = (VGProfileAttributeDefinitionDropDownList) runtime.Groups.GetProfileAttributeDefinition(VGCommonProfileDataType.DropDownList);
profileAttribteDef.Items = new string[] { "Zone 1", "Zone 2", "Zone 3" };
profileAttribteDef.DefaultValue = "Zone 1";

var attrBranchZone = runtime.Groups.CreateProfileAttribute("BranchZone",VGCommonProfileDataType.DropDownList, "BranchZone", "This attribute represents if branch is active", true, false, false, true, 1, "Basic Information", profileAttribteDef);

Create group profile attributes

//Create group profile attributes
var attrBranchCode = runtime.Groups.CreateProfileAttribute("BranchCode",VGCommonProfileDataType.String, "BranchCode", "This attribute represents a branch code");
var attrBranchActive = runtime.Groups.CreateProfileAttribute("IsBranchActive", VGCommonProfileDataType.Boolean, "IsActive", "This attribute represents if branch is active");


var profileAttribteDef = (VGProfileAttributeDefinitionDropDownList) runtime.Groups.GetProfileAttributeDefinition(VGCommonProfileDataType.DropDownList);
profileAttribteDef.Items = new string[] { "Zone 1", "Zone 2", "Zone 3" };
profileAttribteDef.DefaultValue = "Zone 1";

var attrBranchZone = runtime.Groups.CreateProfileAttribute("BranchZone",VGCommonProfileDataType.DropDownList, "BranchZone", "This attribute represents if branch is active", true, false, false, true, 1, "Basic Information", profileAttribteDef);

Get group profile values.

string branchCode = groupHRBranchA.GetValue<string>("BranchCode");
bool isBranchActive = groupHRBranchA.GetValue<bool>("IsBranchActive");
string branchZone = groupHRBranchA.GetValue<string>("BranchZone");

Save/Update group profile values

//Save/Update group profile values
groupHRBranchA.SetValue<string>(attrBranchCode.Id, "Code_442");
groupHRBranchA.SetValue<bool>(attrBranchActive.Id, true);
groupHRBranchA.SetValue<string>(attrBranchZone.Id, "Zone 2");

runtime.Groups.UpdateGroup(groupHRBranchA);

//Save/Update group profile values
groupHRBranchB.SetValue<string>(attrBranchCode.Id, "Code_443");
groupHRBranchB.SetValue<bool>(attrBranchActive.Id, false);
groupHRBranchB.SetValue<string>(attrBranchZone.Id, "Zone 1");

runtime.Groups.UpdateGroup(groupHRBranchB);


Get all groups from VGRepository depending on rights of the user

 //Get all groups
var allGroups = runtime.Groups.GetAllGroup();

//Get all descendant groups of particular group
var childGroups =runtime.Groups.GetAllDescendantGroupsFromGroup(groupHR);

//Get all parent groups of particular group
var parentGroups = runtime.Groups.GetAllParentGroups(groupHRBranchA)

Find groups by various parameters

//find groups by groupname pattern
var findGroups = runtime.Groups.FindGroupsByName("HR Department");
findGroups = runtime.Groups.FindGroupsByName("%Department%");

//find groups by profile attribute
findGroups =  runtime.Groups.FindGroupsByProfileAttributeValue(attrBranchCode.Id, "Code_442");

findGroups = runtime.Groups.FindGroupsByProfileAttributeValue(attrBranchActive.Id, false);
findGroups = runtime.Groups.FindGroupsByProfileAttributeValue(attrBranchActive.Id, true);

findGroups = runtime.Groups.FindGroupsByProfileAttributeValue(attrBranchZone.Id, "Zone 1");
findGroups = runtime.Groups.FindGroupsByProfileAttributeValue(attrBranchZone.Id, "Zone 2");

Assign/Remove user to/from group

var userJsmith = runtime.Membership.GetUser("jsmith");

//assign user to group
runtime.Groups.AddUserToGroup(userJsmith, groupHRBranchA);

//remove user from group
runtime.Groups.RemoveUserFromGroup(userJsmith, groupHRBranchA);

5. How to manage roles ?

Role operations

Add following namespaces in your code

using Novalys.VisualGuard.Security;
using Novalys.VisualGuard.Security.Common;
using Novalys.VisualGuard.Security.CommonProfileAttribute;
using Novalys.VisualGuard.Security.Database;
using Novalys.VisualGuard.Security.Membership;
using Novalys.VisualGuard.Security.UserProfile;
using System;
using System.Collections.Generic;

Define VisualGuard runtime

VGSecurityRuntime runtime = VGSecurityManager.Runtime;


Create/Update/Delete VGRole

//Create / Update / Delete role

var currentApp = runtime.Application.GetCurrentApplication();

//Creates a new role in current application
var roleHR = runtime.Roles.CreateRole("Role_HROperations", "Role HR operations", currentApp);
var roleEmp = runtime.Roles.CreateRole("Role_EmployeeOperations", "Role Employee Operations", currentApp);

//creates a new shared role (shared between multiple applications)
var sharedRole = runtime.Roles.CreateSharedRole("SharedRole", "This is shared Role");

roleHR.Comment = "This role is responsible for HR operations ";           

//update role
runtime.Roles.UpdateRole(roleHR);

//delete role
runtime.Roles.DeleteRole(roleEmp, true);


Create role profile attributes

//Create role profile attributes 
//various datatypes supported - few examples
var attr_A = runtime.Roles.CreateProfileAttribute("AttrA", VGCommonProfileDataType.String);
var attr_B = runtime.Roles.CreateProfileAttribute("AttrB", VGCommonProfileDataType.Boolean);
var attr_C = runtime.Roles.CreateProfileAttribute("AttrC", VGCommonProfileDataType.DateTime);
var attr_D = runtime.Roles.CreateProfileAttribute("AttrD", VGCommonProfileDataType.Integer);


Get role profile values.

string attrA = roleHR.GetValue<string>("AttrA");
bool attrB = roleHR.GetValue<bool>("AttrB");
DateTime attrC = roleHR.GetValue<DateTime>("AttrC");
int attrD = roleHR.GetValue<int>("AttrD");


Save/Update role profile values

roleHR.SetValue<string>(attr_A.Id, "Some information");
roleHR.SetValue<bool>(attr_B.Id, true);
roleHR.SetValue<DateTime>(attr_C.Id, DateTime.Now.Date);
roleHR.SetValue<int>(attr_D.Id, 100);

runtime.Roles.UpdateRole(roleHR);


Get roles from storage depending on rights of the user

//Get all roles (all application's roles)
VGRoleCollection roles = runtime.Roles.GetAllRolesAsCollection();

//get all shared roles
VGRoleCollection sharedroles = runtime.Roles.GetAllSharedRolesAsCollection();

//get all roles of current application
//var currentApp = runtime.Application.GetCurrentApplication();
var currentAppRoles = runtime.Roles.GetAllRolesAsCollection(currentApp);

//get all roles for particular user
var tempJsmithUser = runtime.Membership.GetUser("jsmith");
var userRoles = runtime.Roles.GetAllRolesForUser(tempJsmithUser);


Find roles(by rolename, role profile values)

//find roles by name
var findRoles = runtime.Roles.FindRolesByName("Role_HROperations", currentApp.Id);

//find roles by profile attribute
var findRolesCollection = runtime.Roles.FindRolesByProfileAttributeValue(attr_A.Id, "Some information");
findRolesCollection = runtime.Roles.FindRolesByProfileAttributeValue(attr_B.Id, true);
findRolesCollection = runtime.Roles.FindRolesByProfileAttributeValue(attr_C.Id, DateTime.Now.Date);
findRolesCollection = runtime.Roles.FindRolesByProfileAttributeValue(attr_D.Id, 100);


Grant/Revoke a role to/from user

//Grant a role to user
tempJsmithUser = runtime.Membership.GetUser("jsmith");
runtime.Roles.AddUserToRole(tempJsmithUser, roleHR);

//revoke a role from user
runtime.Roles.RemoveUserFromRole(tempJsmithUser, roleHR);


Grant/revoke permissions to/from role

//grant permission to role
runtime.Roles.GrantPermissionToRole(roleHR, perm_CanManageEmployeeProfile);
runtime.Roles.GrantPermissionToRole(roleHR, perm_CanManageLeavePolicy);

//revoke permission from role
runtime.Roles.RevokePermissionFromRole(roleHR, perm_CanManageLeavePolicy);


Grant/revoke permissionsets to/from role

//grant ps to role
runtime.PermissionSets.GrantPermissionSetToRole(roleHR, ps_HR);

//revoke ps from role
runtime.PermissionSets.RevokePermissionSetToRole(roleHR, ps_HR);

6. How to manage PermissionSet & Permissions ?

PermissionSets/Permissions operations

Add following namespaces in your code

using Novalys.VisualGuard.Security;
using Novalys.VisualGuard.Security.Common;
using Novalys.VisualGuard.Security.CommonProfileAttribute;
using Novalys.VisualGuard.Security.Database;
using Novalys.VisualGuard.Security.Membership;
using Novalys.VisualGuard.Security.UserProfile;
using System;
using System.Collections.Generic;

Define VisualGuard runtime

VGSecurityRuntime runtime = VGSecurityManager.Runtime;


Create/Update/Delete permissionset

//Get current application
var currentApp = runtime.Application.GetCurrentApplication();

//create permissionset
var ps_HR= runtime.PermissionSets.CreatePermissionSet("HR_permissions", "It contains a collection of HR permissions", currentApp);
var ps_temp = runtime.PermissionSets.CreatePermissionSet("temp_permissionset", "temp permissionSet", currentApp);

//update permissionset
ps_HR.Comment = "updated description of ps";
ps_HR.Name = "permissionset_HR";

runtime.PermissionSets.UpdatePermissionSet(ps_HR);

//delete permissionset
runtime.PermissionSets.DeletePermissionSet(ps_temp);


Get permissionsets from storage

//get permissionsets for all applications depending on user rights
var allPermissionsets = runtime.PermissionSets.GetAllPermissionSets(0, int.MaxValue);

//get permissionsets of current application
var appPermissionsets = runtime.PermissionSets.GetPermissionSetByApplication(currentApp, 0, int.MaxValue);


Create/Update/Delete permissions

//create permission
var perm_CanManageEmployeeProfile = runtime.Permissions.CreatePermission(currentApp,"CanManageEmployeeProfile", "CanManageEmployeeProfile permission");
var perm_CanManageLeavePolicy = runtime.Permissions.CreatePermission(currentApp, "CanManageLeavePolicy", "CanManageLeavePolicy permission");

//update permission
perm_CanManageEmployeeProfile.Description = "updated description of CanManageEmployeeProfile";
perm_CanManageEmployeeProfile.Name = "Perm_CanManageEmployeeProfile";

runtime.Permissions.UpdatePermission(perm_CanManageEmployeeProfile);

//delete permission
runtime.Permissions.DeletePermission(perm_CanManageLeavePolicy);


Get permissions

//Get All permission folders
var folders = runtime.Permissions.GetAllFolderByAppId(currentApp.Id);

//get all permissions of current application
var appPermissions = runtime.Permissions.GetAllPermissionByApp(currentApp);

//get all permissions of role
var rolePermissions = runtime.Permissions.GetAllPermission(roleHR);

//get all permissions of group, this method includes children groups
var groupPermissions = runtime.Permissions.GetAllPermission(groupHR);

//get all permissions of particular folder
var folderId = folders[0].Id;
var folderPermissions = runtime.Permissions.GetPermissionsByFolderId(currentApp, folderId);


Grant/revoke permissions to/from ps

//grant permissions to permissionset
runtime.PermissionSets.GrantPermissionToPermissionSet(perm_CanManageEmployeeProfile, ps_HR);
runtime.PermissionSets.GrantPermissionToPermissionSet(perm_CanManageLeavePolicy, ps_HR);

//revoke permission from permissionset
runtime.PermissionSets.RevokePermissionToPermissionSet(perm_CanManageLeavePolicy, ps_HR);


Grant/revoke permissionsets to/from permissionsets

//grant permissionset to permissionset
runtime.PermissionSets.GrantPermissionSetToPermissionSet(ps_temp, ps_HR);

//revoke permissionset from permissionset
runtime.PermissionSets.RevokePermissionSetToPermissionSet(ps_temp, ps_HR);

7. How to manage logging ?

  • EventId – Unique identifier of log entry.
  • ApplicationId – Unique identifier of the application for which the log entry was generated.
  • UserId – Repository ID of the current user.
  • TimeStamp – Date and time of the log entry message.
  • MachineName – Name of the computer.
  • Title – Title of the log entry message.
  • Message – Body of the log entry message.
  • Severity – Log entry severity as a TraceEventType enumeration

Audit (Event Log) operations

Add the following namespaces in your code

using Novalys.VisualGuard.Security;
using Novalys.VisualGuard.Security.Common;
using Novalys.VisualGuard.Security.CommonProfileAttribute;
using Novalys.VisualGuard.Security.Database;
using Novalys.VisualGuard.Security.Logging;
using Novalys.VisualGuard.Security.Membership;
using Novalys.VisualGuard.Security.UserProfile;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;

Define the Visual Guard runtime

VGSecurityRuntime runtime = VGSecurityManager.Runtime;


Get all Event Logs from the storage

var currentApp = runtime.Application.GetCurrentApplication();

//get all event logs, for an application
var logs = runtime.EventLogs.GetAllEventLogByApplication(currentApp);

//get all event logs, for an application, for a given date range
int totalLogs = 0;

DateTime startDate = DateTime.Now.Date.Subtract(new TimeSpan(30, 0, 0, 0));
DateTime endDate = DateTime.Now.Date;            

//get all event logs, for a particular user, for all applications, for a given date range
var logsbyUsername = runtime.EventLogs.GetAllEventLogByUsername("jsmith", startDate, endDate, 0, int.MaxValue, out totalLogs);

//Get all event logs, for all applications
var allEventLogs= runtime.EventLogs.GetAllEventLog();

//Get event logs by category
var logsByCategory = runtime.EventLogs.GetAllEventLogByCategory(VGLogCategory.AccountLogon, startDate, endDate);


Add your own Custom Event ID

//few examples for adding new custom event IDs 
runtime.EventLogs.AddCustomVGEventId(101, "Viewing employee");
runtime.EventLogs.AddCustomVGEventId(102, "Viewing customer");
runtime.EventLogs.AddCustomVGEventId(103, "Change employee salary");
runtime.EventLogs.AddCustomVGEventId(104, "Viewing sales order");
runtime.EventLogs.AddCustomVGEventId(105, "SalesOrder modified");
runtime.EventLogs.AddCustomVGEventId(106, "SalesOrder deleted");


Write an Event Log

//define properties
StringDictionary dictionary = new StringDictionary();
dictionary.Add("Id", "143");
dictionary.Add("EmployeeName", "Peter");

//define a log entry
var logentry_ViewEmployee = new VGLogEntry(101, "View Employee", "Consultation of Employee: [p:EmployeeName] [p:Id]", System.Diagnostics.TraceEventType.Information, dictionary);

//write log for an application
runtime.WriteLog(logentry_ViewEmployee);


//define a log entry
dictionary.Add("OldSal", "5000");
dictionary.Add("NewSal", "6000");
var logentry_ChangeEmployeeSalary = new VGLogEntry(103, "Change employee salary", "Changed employee salary from [p:OldSal] to [p:NewSal], for employee: [p:EmployeeName] ", System.Diagnostics.TraceEventType.Information, dictionary);


//write log for an application
runtime.WriteLog(logentry_ChangeEmployeeSalary);

//you can also use the following methods for writing logs
Security.Logging.VGLogger.Write(logentry_ViewEmployee);
VGSecurityManager.WriteLog(logentry_ViewEmployee);


Get all custom event IDs

 //Get all custom event Ids
var allCustomEventIds = runtime.EventLogs.GetAllCustomEventIds();


Delete a custom event ID

//find a particular Event ID
var findEventId = allCustomEventIds.Find(x => x.EventId == 106);

//Delete a custom Event ID
runtime.EventLogs.DeleteCustomVGEventId(findEventId);


Clear logs

 //clear all logs, for the current application
runtime.EventLogs.ClearLog(currentApp);

//clear logs older than 15 days, for the current application 
runtime.EventLogs.ClearLog(currentApp,DateTime.Now.Date.Subtract(new TimeSpan(15,0,0,0)));

8. How to debugging Visual Guard ?

  • Why my user is rejected during the authentication process?
  • Is my permission is granted to the current user.
  • What is the value of my permission argument?
  • Why a security action is not executed?

Visual Guard: *******************************************************
Visual Guard: ==> 2006-08-23 13:27:22Z: Visual Guard initialization
Visual Guard: ==> 2006-08-23 13:27:23Z: Repository provider loaded: Novalys.VisualGuard.Security.Files.Repository.VGFileRepositoryConnection, Novalys.VisualGuard.Security.File, Version=2.5.708.6, Culture=neutral, PublicKeyToken=8e423a8f05ffd0dc
Visual Guard: Authorization attempt: user=jsmith (status=Success)
Visual Guard: Granted Role: #Sales manager (#Sales manager)
Visual Guard:     Granted permissions:
Visual Guard:         [Sales manager permissions].\Employees\Disable employees edition (id=8f95817d-ac24-4fd1-90d7-49a42eacd156)
Visual Guard:         [Sales manager permissions].\Products\Disable products and categories edition (id=bb241aa9-24ce-4b5b-96d3-4bf16db4e174)
Visual Guard:         [Common permissions].\Samples\Permission with argument(MyValue = My default value) (id=07b21eb4-4bef-4a0d-83aa-adb90c31a992)
Visual Guard:         [Common permissions].\Samples\Script Action Sample(Attribute1 = "My Value for attribute1", Attribute2 = 31/12/2006 00:00:00) (id=c755dfa1-73a3-47cd-8260-b4f6c20e3018)
Visual Guard:         [Non administrator permissions].\Users\Disable Membership edition (id=042e30c2-ca0f-4ce8-931f-8290fe98417e)
Visual Guard: Authentication attempt: user=jsmith (status=Success)
Visual Guard: ==> 2006-08-23 13:27:30Z: Set Security of Novalys.VisualGuard.NorthwindSample.Common.Data.SecuredNorthwindDataset
Visual Guard: ==> 2006-08-23 13:27:30Z: Set Security of Novalys.VisualGuard.NorthwindSample.MDIForm
Visual Guard: ==> 2006-08-23 13:27:30Z: Execute Action \Products\Disable products and categories edition.MDIForm.SetProperties(_myCategories.Enabled=False,_myProducts.En...)
Visual Guard: ==> 2006-08-23 13:27:30Z: Execute Action \Samples\Script Action Sample.MDIForm.SetProperties(_editConfigToolStripMenuItem.Visible=False)
Visual Guard: ==> 2006-08-23 13:27:30Z: == Action condition 'Enabled = true' is True => Action executed
Visual Guard: ==> 2006-08-23 13:27:30Z: Execute Action \Users\Disable Membership edition.MDIForm.SetProperties(_usersMenuItem.Enabled=False)


How to generate a trace in release mode

void VGModule_Initialized(object sender, Novalys.VisualGuard.Security.WebForm.VGSecurityInitializedEventArgs e)
{
    // Trace all information in a MyTrace.txt at the root of the website 
    string path = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, "MyTrace.Txt");

    System.Diagnostics.TextWriterTraceListener listener;

    listener = new System.Diagnostics.TextWriterTraceListener(new System.IO.FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite));

    Novalys.VisualGuard.Security.VGSecurityManager.TraceLevel = System.Diagnostics.TraceLevel.Info;
    Novalys.VisualGuard.Security.VGSecurityManager.TraceListener = listener;
}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <switches>
            <add name="VisualGuard" value="3" />
        </switches>              
        <trace autoflush="false" indentsize="4">
          <listeners>
            <add name="VisualGuard" type="System.Diagnostics.TextWriterTraceListener" initializeData="VGLog.txt" />
            <remove name="Default" />
          </listeners>
        </trace>
    </system.diagnostics>          
</configuration>


Debugging dynamic script action