/// <summary>Fetch circuit Id from grid element id.</summary> /// <remarks>Circuit Id composed of the first 7 segments.</remarks> public static string GetCircuitId(BplIdentity gridElementId) { try { string[] s = gridElementId.LocalId.ToString().Split('.'); return string.Format("{0}.{1}.{2}.{3}.{4}.{5}.{6}", s[0], s[1], s[2], s[3], s[4], s[5], s[6]); } catch (Exception) { throw new Exception(string.Format("Element id:{0} contains less than 7 segments which used to identify a circuit", gridElementId)); } }
/// <summary>Adds a target object and indexes it under the specified id.</summary> /// <returns><c>true</c> if the target was successfully added; <c>false</c> if an object with the specified id already exists.</returns> public bool AddTarget(BplIdentity targetId, BplObject target) { if (_targets.ContainsKey(targetId)) { return false; } else { _targets[targetId] = target; return true; } }
private string _createNewAuthorizationToken(BplIdentity driverId, IEnumerable<Contact> associatedContacts, MultiString contactName, AuthorizationSessionKind kind) { var session = new DriverAuthorizationSessionData { DriverId = driverId, SessionStart = TimeStamp.LocalNow, //SessionKind = kind IsRegistration = kind == AuthorizationSessionKind.Registration }; if (associatedContacts != null) { session.LoginContacts.AddRange(associatedContacts.Select(c => new LoginContact(c))); session.LoginContacts.Apply(c => c.ContactName = contactName); } return CryptServices.Encode(session); }
/// <summary/> protected override void SetSessionIdOverride(BplIdentity sessionId) { if (SessionData != null) SessionData.SessionId = sessionId; }
internal static string GetLoginName(BplIdentity id) { using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) { using (var up = UserPrincipal.FindByIdentity(context, IdentityType.Name, (string)id.LocalId)) { return up != null ? up.SamAccountName : null; } } }
public InboxEntry Remove(BplIdentity id) { lock (this) { var entry = _inbox.FirstOrDefault(e => e.Request.Id == id); _inbox.Remove(entry); return entry; } }
public FrmDiagnosticsTaskAddUpdate(BplIdentity taskId) { InitializeComponent(); _taskId = taskId; }
public DeviceInstallDeleteByDeviceId(BplIdentity deviceId) { DeviceId = deviceId; }
public void RequestDriverInfo(BplIdentity driverId, bool isReplyRequired) { var info = new GetSubscriberInfo { SubscriberId = driverId }; var server = (OscarServer)(OscarServer.Current); _isReplyRequired = isReplyRequired; Forward(info, _onSuccess, _onFailure); }
public void RequestVehicleInfo(BplIdentity vehicleId) { var info = new GetVehicleInfo { VehicleId = vehicleId }; var server = (OscarServer)(OscarServer.Current); Forward(info, _onSuccess, _onFailure); }
public IAsyncResult BeginGetBatterySnByVehicleID(BplIdentity vehicleId, AsyncCallback callback, object asyncState) { throw new NotImplementedException(); }
public FrmSelectDevice(BplIdentity platformId) { InitializeComponent(); _platformId = platformId; }
private bool _isExcluded(BplIdentity deviceId) { if (_excludedDevices == null || _excludedDevices.Count == 0) { return false; } foreach (var di in _excludedDevices) { if (deviceId.LocalId.ToString() == di.DeviceId.LocalId.ToString()) { return true; } } return false; }
internal static bool IsFactory(BplIdentity id) { return IsFactory(id.LocalId.ToString()); }
private void _checkDriver(BplIdentity DriverId, string RegistrationCode, AuthorizationSessionKind actionKind, Action<DriverAuthorizationResult> onSuccess, Action<GeneralFailure> onFailure) { if (DriverId == null || RegistrationCode.IsEmpty()) { Log.Warn("Driver registration: Attempt to check driver with bad arguments. UserId:{0}, UserSsn:{1}", DriverId, RegistrationCode); onSuccess(new DriverAuthorizationResult { Result = RegistrationResult.InvalidInformation }); } else { var di = new GetDriverInfo { DriverId = DriverId }; Services.Invoke(di, o => { if (o != null) { if (o.DriverSsn.EqualsIgnoreCase(RegistrationCode)) { Log.Info("Driver registration: Initialized for driver '{0}'.", DriverId); var contacts = o.Contacts.Where(c => c.Type == ContactTypes.MobilePhone || c.Type == ContactTypes.Email).Select(c => c.Clone()); var result = new DriverAuthorizationResult { Result = RegistrationResult.Success, Token = _createNewAuthorizationToken(DriverId, contacts, o.Name, actionKind) }; result.Contacts.AddRange(contacts); if (result.Contacts.Count > 0) { onSuccess(result); } else { Log.Warn("Driver registration: Driver '{0}' has no valid contact information.", DriverId); onSuccess(new DriverAuthorizationResult { Result = RegistrationResult.InvalidInformation }); } } else { Log.Warn("Driver registration: Driver '{0}' SSN ({1}) not matches database value ({2}).", DriverId, RegistrationCode, o.DriverSsn); onSuccess(new DriverAuthorizationResult { Result = RegistrationResult.InvalidInformation }); } } else { Log.Warn("Driver registration: Driver '{0}' is not found in database or blocked.", DriverId); onSuccess(new DriverAuthorizationResult { Result = RegistrationResult.ClientBlocked }); } }, e => onFailure(e) ); } }
internal static SwlResult CampaignTargetSetStatus(DbConnector dbConn, BplIdentity targetId, Mpcr.Services.Oscar.Logistics.CampaignTargetStatus status) { var ti = dbConn.ExecuteBpl(new CampaignTargetGetById { TargetId = targetId }); if (ti == null) { return SwlResult.NOT_FOUND; } switch (status) { case CampaignTargetStatus.Success: dbConn.ExecuteBpl(new CampaignTargetUpdateProgress { TargetId = targetId, ClientUpdateState = SoftwareUpdateState.Completed, ClientUpdateStatus = "Update completed successfully" }); break; case CampaignTargetStatus.Failed: dbConn.ExecuteBpl(new CampaignTargetUpdateProgress { TargetId = targetId, ClientUpdateState = SoftwareUpdateState.Failed, ClientUpdateStatus = "Update failed" }); break; } dbConn.ExecuteBpl(new CampaignTargetChangeStatus { TargetId = targetId, Status = status }); return CampaignCheckStatus(dbConn, ti.CampaignId); }
public static SwlResult CampaignTargetCompletion(DbConnector dbConn, BplIdentity targetId, SoftwareUpdateResult updateResult) { var target = dbConn.ExecuteBpl(new CampaignTargetGetById { TargetId = targetId }); if (target == null) { Log.Warn("CAMPAIGN TARGET with ID {0} not found in database, EXITING !!!", targetId); return SwlResult.NOT_FOUND; } var targetStatus = CampaignTargetStatus.Failed; if (updateResult == SoftwareUpdateResult.Success) { var di = dbConn.ExecuteBpl(new DeviceGetById { DeviceId = target.DeviceId }); if (di == null) { Log.Error("Device with ID: {0} not found in database, EXITING !!!", target.DeviceId); return SwlResult.INVALID_DATA; } dbConn.ExecuteBpl(new DeviceInstallAdd(di.DeviceId, target.CampaignType, target.CampaignDstInstallId)); targetStatus = CampaignTargetStatus.Success; } return LogisticsHelpers.CampaignTargetSetStatus(dbConn, targetId, targetStatus); }
private static bool _applyImplicitValue(BplContextNode input, BplProperty property, BplIdentity implicitValue) { var inputValue = (BplIdentity)property.GetValue(input); if (inputValue.IsEmpty) { property.SetValue(input, implicitValue); return true; } else { return inputValue == implicitValue; } }
public DeviceInstallAdd(BplIdentity deviceId, SoftwareUpdateType installType, BplIdentity installId) { DeviceId = deviceId; InstallType = installType; InstallId = installId; }
public FrmSelectInstall(BplIdentity platformId, SoftwareUpdateType type) { InitializeComponent(); _platformId = platformId; _type = type; }
/// <summary>Override this method on derived message classes to set the session id.</summary> protected abstract void SetSessionIdOverride(BplIdentity sessionId);
internal static SwlResult InstallAddNewImage(DbConnector dbConn, BplIdentity requestPlatformId, string requestCodeName, string sourcePath) { sourcePath = Path.Combine(LogisticsHelpers.PathTemp, sourcePath); var tempImageFile = Path.Combine(sourcePath, InstallImageFileName); var tempMasterPackageFile = Path.Combine(sourcePath, InstallMasterPackageFileName); var imageHdr = Interop.GetImageHeader(tempImageFile); if (imageHdr == null) { Log.Error("Bad image file {0}", tempImageFile); return SwlResult.INVALID_DATA; } var platformId = BplIdentity.Get(string.Format("{0:X08}", imageHdr.Value.PlatformId)); if (platformId != requestPlatformId) { Log.Error("Platform id ({0}) in request is not equal image file platform id ({1})", requestPlatformId, platformId); return SwlResult.INVALID_PLATFORM; } var pi = dbConn.ExecuteBpl(new PlatformGetById(platformId)); if (pi == null) { pi = new PlatformInfo(); pi.PlatformId = platformId; pi.PlatformUId = (int)imageHdr.Value.PlatformId; pi.PlatformName = imageHdr.Value.PlatformName; pi.PlatformVersion = imageHdr.Value.PlatformVersion.ToInt32(); dbConn.ExecuteBpl(new PlatformAdd(pi)); dbConn.ExecuteBpl(new PlatformSetLock(platformId, PlatformLockType.ByClient, BplIdentity.Empty)); } var ii = dbConn.ExecuteBpl(new InstallGetByPlatformIdTypeVersionNumber(pi.PlatformId, Mpcr.Services.Oscar.Logistics.SoftwareUpdateType.Image, imageHdr.Value.Version.ToInt32())); if (ii != null) { return SwlResult.ALREADY_EXISTS; } ii = new InstallInfo(); ii.InstallId = BplIdentity.Get(string.Format("PLID{0:X08}-IID{1:000}{2:000}{3:00000}", imageHdr.Value.PlatformId, imageHdr.Value.Version.Major, imageHdr.Value.Version.Minor, imageHdr.Value.Version.Release)); ii.Type = Mpcr.Services.Oscar.Logistics.SoftwareUpdateType.Image; ii.PlatformId = platformId; ii.VersionNumber = imageHdr.Value.Version.ToInt32(); ; ii.Description = imageHdr.Value.Desc; ii.Date = imageHdr.Value.Date.ToDateTime(); ii.Status = InstallStatus.Ready; ii.CodeName = requestCodeName; var installStoragePath = LogisticsHelpers.InstallGetStoragePath(ii); Directory.CreateDirectory(installStoragePath); File.Move(tempImageFile, Path.Combine(installStoragePath, LogisticsHelpers.InstallImageFileName)); File.Move(tempMasterPackageFile, Path.Combine(installStoragePath, LogisticsHelpers.InstallMasterPackageFileName)); Directory.Delete(sourcePath, true); dbConn.ExecuteBpl(new InstallAdd(ii)); var swlr = LogisticsHelpers.InstallCreatePackages(dbConn, ii.InstallId); if (swlr != SwlResult.OK) { return swlr; } return SwlResult.OK; }
internal static SwlResult InstallCreatePackages(DbConnector dbConn, BplIdentity installId) { var installInfo = dbConn.ExecuteBpl(new InstallGetById(installId)); if (installInfo == null) { return SwlResult.NOT_FOUND; } if (installInfo.Status != InstallStatus.Ready) { return SwlResult.NOT_READY; } installInfo.Status = InstallStatus.Busy; dbConn.ExecuteBpl(new InstallSetStatus(installInfo)); var packages = dbConn.ExecuteBpl(new PackageGetByTargetInstallId { TargetInstallId = installInfo.InstallId }); foreach (var pkg in packages) { PackageDelete(dbConn, pkg, installInfo.Type); } var platformInstalls = dbConn.ExecuteBpl(new InstallGetByPlatformId(installInfo.PlatformId)); foreach (var inst in platformInstalls) { var currentVersion = SwlVersion.FromInt32(installInfo.VersionNumber); var sourceVersion = SwlVersion.FromInt32(inst.VersionNumber); if (SwlVersion.Compare(sourceVersion, currentVersion) >= 0) { continue; } var sourceDescriptor = dbConn.ExecuteBpl(new InstallGetRuntimeDescriptor(inst.InstallId)); if ((sourceDescriptor == null) || (sourceDescriptor.Length == 0)) { continue; } var pkgInfo = new PackageInfo(); pkgInfo.PackageId = BplIdentity.Get(string.Format("PLID{0}-T{1:000}{2:000}{3:00000}-F{4:000}{5:000}{6:00000}", installInfo.PlatformId.LocalId.ToString(), currentVersion.Major, currentVersion.Minor, currentVersion.Release, sourceVersion.Major, sourceVersion.Minor, sourceVersion.Release)); pkgInfo.PackageName = pkgInfo.PackageId.LocalId.ToString() + ".pkg"; var packagePath = Path.Combine(StorageManager.PackagesPath, pkgInfo.PackageName); if (!Interop.CreatePackage(_getInstallMasterPackageFileName(installInfo), sourceVersion, sourceDescriptor, packagePath)) { continue; } pkgInfo.PackageCRC = ComputeCRC(packagePath); pkgInfo.PackageSize = (int)(new FileInfo(packagePath).Length); pkgInfo.TargetInstallId = installInfo.InstallId; pkgInfo.SourceInstallId = inst.InstallId; dbConn.ExecuteBpl(new PackageAdd(pkgInfo)); } installInfo.Status = InstallStatus.Ready; dbConn.ExecuteBpl(new InstallSetStatus(installInfo)); return SwlResult.OK; }
internal static SwlResult InstallDelete(DbConnector dbConn, BplIdentity installId) { var ii = dbConn.ExecuteBpl(new InstallGetById(installId)); if (ii == null) { Log.Error("Installation with id {0} not found", installId); return SwlResult.NOT_FOUND; } var packages = dbConn.ExecuteBpl(new PackageGetByTargetInstallId { TargetInstallId = ii.InstallId }); foreach (var pkg in packages) { LogisticsHelpers.PackageDelete(dbConn, pkg, ii.Type); } packages = dbConn.ExecuteBpl(new PackageGetByTargetInstallId { TargetInstallId = ii.InstallId }); foreach (var pkg in packages) { LogisticsHelpers.PackageDelete(dbConn, pkg, ii.Type); } if (ii.Type == Mpcr.Services.Oscar.Logistics.SoftwareUpdateType.Image) { var installStoragePath = LogisticsHelpers.InstallGetStoragePath(ii); File.Delete(Path.Combine(installStoragePath, LogisticsHelpers.InstallImageFileName)); File.Delete(Path.Combine(installStoragePath, LogisticsHelpers.InstallMasterPackageFileName)); Directory.Delete(installStoragePath, true); } dbConn.ExecuteBpl(new InstallDelete { InstallId = ii.InstallId }); return SwlResult.OK; }
internal static Contact GetClientContact(BplIdentity id) { Contact result = null; try { using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) { using (var up = UserPrincipal.FindByIdentity(context, IdentityType.Name, (string)id.LocalId)) { if (up != null) { if (up.EmailAddress.NotEmpty()) { result = new Contact { Type = ContactTypes.Email, Value = up.EmailAddress }; } else { result = new Contact { Type = ContactTypes.MobilePhone, Value = up.VoiceTelephoneNumber }; } } else { Log.Warn("User {0} was not found", id); } } } } catch (Exception e) { Log.Exception(e, "Unable to get client contact."); } return result; }
internal static SwlResult CampaignCheckStatus(DbConnector dbConn, BplIdentity campaignId) { var ci = dbConn.ExecuteBpl(new CampaignGetById(campaignId)); if (ci == null) { return SwlResult.NOT_FOUND; } var targets = dbConn.ExecuteBpl(new CampaignTargetGetByCampaignId { CampaignId = campaignId }); int pending = 0; int inprogress = 0; int success = 0; int failed = 0; int cancelled = 0; foreach (var target in targets) { switch (target.Status) { case CampaignTargetStatus.Pending: { pending++; break; } case CampaignTargetStatus.Inprogress: { inprogress++; break; } case CampaignTargetStatus.Success: { success++; break; } case CampaignTargetStatus.Failed: { failed++; break; } case CampaignTargetStatus.Canceled: { cancelled++; break; } } } if ((inprogress == 0) && (success == 0) && (failed == 0) && (cancelled == 0)) { ci.CompletionStatus = CampaignCompletionStatus.Pending; } else if (inprogress > 0) { ci.CompletionStatus = CampaignCompletionStatus.Inprogress; ci.WorkStatus = CampaignWorkStatus.Active; } else if (failed > 0) { ci.CompletionStatus = CampaignCompletionStatus.Failed; } else if (cancelled > 0) { ci.CompletionStatus = CampaignCompletionStatus.Stopped; } else { if (success == targets.Count) { ci.CompletionStatus = CampaignCompletionStatus.Success; } } if ((success + failed + cancelled) == targets.Count) { ci.WorkStatus = CampaignWorkStatus.Closed; } dbConn.ExecuteBpl(new CampaignChangeStatus(ci.CampaignId, ci.WorkStatus, ci.CompletionStatus)); return SwlResult.OK; }
internal static void CreateUser(BplIdentity id, LoginContact contact, string password, Action<RegistrationResult, string> onFinished) { //cleanup role var loginName = _getName(contact); if (loginName.IsEmpty() || password.IsEmpty()) { onFinished(RegistrationResult.InvalidInformation, null); } else { try { //register in AD using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) { var result = RegistrationResult.Success; try { var up = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName); if (up != null) { result = up.Enabled == true ? RegistrationResult.ClientAlreadyRegistered : RegistrationResult.ClientBlocked; } else { up = new UserPrincipal(context); up.SamAccountName = loginName; //TK: Consider duplication on up.UserPrincipalName up.Name = (string)id.LocalId; //TODO: Consider not only for drivers. Local ID can be not unique. if (contact.LoginKind == LoginKind.Email) { up.EmailAddress = contact.LoginValue; } else { //this is phone number up.VoiceTelephoneNumber = contact.LoginValue; } up.Save(); object pgid = null; var gpOscar = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, _usersGroup); if (gpOscar != null) { var grp = (DirectoryEntry)gpOscar.GetUnderlyingObject(); grp.Invoke("GetInfoEx", new object[] { new object[] { "primaryGroupToken" }, 0 }); pgid = grp.Invoke("Get", new object[] { "primaryGroupToken" }); grp.Properties["member"].Add(up.DistinguishedName); grp.CommitChanges(); grp.Close(); } else { throw new ApplicationException("Unable to get and assign valid group {0}".Substitute(_usersGroup)); } //this is how we are doing impersonation using (var entry = new DirectoryEntry("LDAP://{0}/{1}".Substitute(ADServer, up.DistinguishedName), ADUsername, ADPassword)) { //TK: consider using reg code -> entry.Properties["uid"].Value = request.RegistrationCode; if (pgid != null) { entry.Properties["primaryGroupID"].Value = pgid; } entry.Invoke("SetPassword", new object[] { password }); entry.CommitChanges(); using (var gContext = new PrincipalContext(ContextType.Domain, ADServer, ADGlobalContainer, ADUsername, ADPassword)) { var gpUsers = GroupPrincipal.FindByIdentity(gContext, "Domain Users"); if (gpUsers != null) { var grp = (DirectoryEntry)gpUsers.GetUnderlyingObject(); grp.Properties["member"].Remove(up.DistinguishedName); grp.CommitChanges(); grp.Close(); } else { throw new ApplicationException("Unable to remove user from domain default group."); } } } up.Enabled = true; up.Save(); result = up.Enabled == true ? RegistrationResult.Success : RegistrationResult.Failure; up.Dispose(); up = null; Log.Info("User {0} registered in AD", loginName); } onFinished(result, loginName); } catch (Exception e) { //check and cleanup user if it is using (var up = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) { if (up != null && up.Enabled != true) { up.Delete(); } } onFinished(RegistrationResult.Failure, null); Log.Exception(e, "Unable to register user in active directory"); } } } catch (Exception dx) { onFinished(RegistrationResult.Failure, null); Log.Exception(dx, "Unable to connect to active directory"); } } }
internal static CampaignTargetInfoEx CampaignTargetCheckForUpdate(DbConnector dbConn, BplIdentity deviceId) { var targets = dbConn.ExecuteBpl(new CampaignTargetGetByDeviceId { DeviceId = deviceId }); if (targets.Count == 0) { return null; } foreach (var target in targets) { if (target.CampaignCompleteonStatus == CampaignCompletionStatus.Failed) { return null; } if (target.CampaignWorkStatus != CampaignWorkStatus.Active) { continue; } if ((int)target.Status < (int)CampaignTargetStatus.Success) { return target; } } return null; }
/// <summary/> protected override void SetSessionIdOverride(BplIdentity sessionId) { SessionId = sessionId; }
/// <summary>Creates a new <see cref="BplPendingReference"/> instance.</summary> public BplPendingReference(BplObject source, BplProperty property, BplIdentity targetId) { Source = source; Property = property; TargetId = targetId; }