/// <summary> /// After the download process is over, /// downloaded files log is updated. /// </summary> /// <param name="fileId">id of the file downloaded</param> public void DownloadFileLog(int fileId) { string machineName = string.Empty; string ipAddress = string.Empty; try { if (!string.IsNullOrEmpty(ConnectionString)) { machineName = System.Environment.MachineName; //Get the machine name ipAddress = HttpContext.Current.Request.UserHostAddress; // Get the IP using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.FileDownloadLog, dbConnection)) { command.CommandType = CommandType.StoredProcedure; // Adding all parameters command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.MachineName, machineName)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.IpAddress, ipAddress)); dbConnection.Open(); command.ExecuteNonQuery(); } } } } catch (SqlException ex) { //Log the error ErrorUtility.WriteError(ex); } }
/// <summary> /// Method to change the password of a locked file /// </summary> /// <param name="fileId">Id of the file </param> /// <param name="newPassword">New password</param> public void ChangeFilePassword(int fileId, string newPassword) { try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.ChangeFilePassword, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.NewPassword, newPassword)); dbConnection.Open(); command.ExecuteNonQuery(); } } } } catch (SqlException ex) { //log the error ErrorUtility.WriteError(ex); } }
/// <summary> /// Save Tiny URL against the file /// </summary> /// <param name="tinyUrl"></param> /// <param name="fileId"></param> public void SaveTinyUrl(string tinyUrl, int fileId) { try { if (!string.IsNullOrEmpty(ConnectionString) && !string.IsNullOrEmpty(tinyUrl)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.SaveTinyUrl, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding all parameters command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.TinyUrl, tinyUrl)); dbConnection.Open(); command.ExecuteNonQuery(); } } } } catch (SqlException ex) { //log the error ErrorUtility.WriteError(ex); } }
/// <summary> /// gets all the registered user's details. /// </summary> /// <param name="searchOperator">the optional param it tells the search operation to be done</param> /// <param name="searchTerm">the term to be searched for</param> /// <returns>datatable of all the users record</returns> public DataTable GetAllUsersDetail(string searchOperator, string searchTerm) { DataTable registeredUsers = new DataTable(); try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetAllUserDetails, connection)) { connection.Open(); command.CommandType = CommandType.StoredProcedure; if (!string.IsNullOrEmpty(searchTerm)) { command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SearchTerm, searchTerm)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SearchOper, searchOperator)); } registeredUsers.Load(command.ExecuteReader()); } } } } catch (SqlException ex) { //Log the error ErrorUtility.WriteError(ex); } return(registeredUsers); }
/// <summary> /// Checks whether a user with the email exists or not /// </summary> /// <param name="email"></param> /// <returns></returns> public bool GetUserByEmail(string email) { bool isUserExist = false; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetUserByEmail, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.Email, email)); dbConnection.Open(); var result = command.ExecuteScalar(); if (result != null) { bool.TryParse(Convert.ToString(result), out isUserExist); } } } } } catch (Exception ex) { //Log the error ErrorUtility.WriteError(ex); } return(isUserExist); }
private static async void Import(WorkspaceViewModel workspace, ConverterType target) { var dialog = new CommonOpenFileDialog { IsFolderPicker = false, Multiselect = false, EnsureFileExists = true, Title = Language.Current.Get("Dialog.Import.Title") }; if (dialog.ShowDialog(Application.Current.MainWindow) == CommonFileDialogResult.Ok) { try { await ImportFile(workspace, dialog.FileName, target); } catch (Exception e) { var errorText = await ErrorUtility.GetErrorMessage(e, workspace.Dispatcher); workspace.Messages.Error(errorText); } } dialog.Dispose(); }
public void Execute() { Console.WriteLine("doc Started."); try { //fetch all the resources to be uploaded AssetDataFactory _dataFactory = new AssetDataFactory(); S3Uploader cdnManager = new S3Uploader(); int chunckSize = 0; Console.WriteLine("Fetch asset for syncing"); int totalCount = _dataFactory.GetAppointmentAssetCount((int)AssetTypes.Appointment_Document, true); Console.WriteLine("Upload asset is in progress"); do { List <Assets> assets = _dataFactory.GetAppointmentAsset((int)AssetTypes.Appointment_Document, true, 2);//asset type //loop through each asset and upload to CDN foreach (var item in assets) { var assetRequest = new UploadAssetRequestParameters(); string directoryName = Path.GetDirectoryName(item.TargetPath); //int pos = item.TargetPath.LastIndexOf("/") + 1; string bucketRelativePath = directoryName;//item.TargetPath.Substring(0, pos); assetRequest.BucketName = ConfigurationManager.AppSettings["S3BucketName"] + @"/private/" + directoryName; assetRequest.FilePath = ConfigurationManager.AppSettings["FileStoreRoot"] + item.TargetPath; assetRequest.Tags = new Dictionary <string, string>() { { "Asset Type", "Appointment Document" }, { "Asset Id", item.AssetId.ToString() } }; if (item.AppointmentAssets.Count > 0) { assetRequest.Tags.Add("Asset Entity Id", item.AppointmentAssets.FirstOrDefault().appointmentID.ToString()); } int monthDiff = S3Uploader.GetMonthDifference(DateTime.UtcNow, item.UpdatedDateTime ?? item.CreatedDateTime.Value); S3StorageClass storageClass = S3StorageClass.Standard; if (monthDiff > 6 && monthDiff < 36) { storageClass = S3StorageClass.StandardInfrequentAccess; } else if (monthDiff > 36) { storageClass = S3StorageClass.Glacier; } string objectKey = cdnManager.UploadFile(assetRequest, storageClass); if (!string.IsNullOrEmpty(objectKey)) { _dataFactory.UpdateAssetPath(item.AssetId, bucketRelativePath + objectKey); } } chunckSize = chunckSize + 2; } while (totalCount > chunckSize); Console.WriteLine("Upload asset is completed"); } catch (Exception e) { ErrorUtility.LogError(e, GartnerApplication.Unknown, string.Format("Error: Upload Doc error: " + e.Message)); } }
public ActionResponseExceptionDetail(string code = "", string additionalCode = "") { this.FriendlyMessageCode = code; if (!string.IsNullOrEmpty(additionalCode)) { this.AdditionalDetailsErrorMessage = ErrorUtility.GetAdditionalDetailsMessage(additionalCode); } }
/// <summary> /// Get the user details from the login table /// i.e checks whether the user exists or not /// </summary> /// <param name="email">registered email id</param> /// <param name="password">password of the user</param> /// <returns>user type object with all the reqd. details </returns> public User GetUserDetails(string email, string password) { SqlDataReader reader = null; User user = null; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetUserDetails, dbConnection)) { command.CommandType = CommandType.StoredProcedure; // Adding all parameters command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.Email, email)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.Password, password)); dbConnection.Open(); reader = command.ExecuteReader(); //Read data using datareader if (reader.HasRows && reader.Read()) { user = new User(); if (reader[ConstantUtility.UserHashcode] != DBNull.Value) { user.UserHashCode = Convert.ToString(reader[ConstantUtility.UserHashcode]); } if (reader[ConstantUtility.UserName] != DBNull.Value) { user.UserName = Convert.ToString(reader[ConstantUtility.UserName]); } if (reader[ConstantUtility.IsAdmin] != DBNull.Value) { user.IsAdmin = Convert.ToBoolean(reader[ConstantUtility.IsAdmin]); } } } } } } catch (SqlException ex) { //log the error ErrorUtility.WriteError(ex); } finally { reader.Close(); } return(user); }
private static async Task LifecycleConfigAsync() { client = new AmazonS3Client(bucketRegion); string input = Console.ReadLine(); try { int action = Convert.ToInt32(input); var lifeCycleConfiguration = new LifecycleConfiguration(); switch (action) { case 1: await AddUpdateDeleteLifecycleConfigAsync(); break; case 2: lifeCycleConfiguration = await RetrieveLifecycleConfigAsync(client); foreach (var rule in lifeCycleConfiguration.Rules) { Console.WriteLine("Rule Id {0} with status of {1} and expiration Days is ", rule.Id, rule.Status, rule.Expiration != null ? rule.Expiration.Days: 0); Console.WriteLine("Transition"); foreach (var trans in rule.Transitions) { Console.WriteLine("Storage class {0} and expiration Days is ", trans.StorageClass, trans.Days); } Console.WriteLine("Filter"); if (rule.Filter.LifecycleFilterPredicate is LifecyclePrefixPredicate) { LifecyclePrefixPredicate prefix = rule.Filter.LifecycleFilterPredicate as LifecyclePrefixPredicate; Console.WriteLine("Filter Prefix {0} and expiration Days is ", prefix.Prefix); } if (rule.Filter.LifecycleFilterPredicate is LifecycleTagPredicate) { LifecycleTagPredicate tags = rule.Filter.LifecycleFilterPredicate as LifecycleTagPredicate; Console.WriteLine("Filter Tag Key {0} and value ", tags.Tag.Key, tags.Tag.Value); } Console.WriteLine("*************************************"); } break; case 3: await RemoveLifecycleConfigAsync(client); break; default: break; } } catch (Exception e) { ErrorUtility.LogError(e, GApplication.Unknown, string.Format("Error: Lifecycle Error: " + e.Message)); } }
/// <summary> /// Gets the name of the file using file id /// </summary> /// <param name="fileId">id of the file whose name is required</param> /// <returns>Name of the file</returns> public UploadedFile GetFileName(int fileId) { UploadedFile objFileDetails = null; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetFileName, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); dbConnection.Open(); SqlDataReader reader = command.ExecuteReader(); //Read data using datareader if (reader.HasRows && reader.Read()) { objFileDetails = new UploadedFile(); if (reader[ConstantUtility.NewFileName] != DBNull.Value) { objFileDetails.NewFileName = Convert.ToString(reader[ConstantUtility.NewFileName]); } if (reader[ConstantUtility.SavedFileName] != DBNull.Value) { objFileDetails.SavedFileName = Convert.ToString(reader[ConstantUtility.SavedFileName]); } if (reader[ConstantUtility.ThumbName] != DBNull.Value) { objFileDetails.ThumbName = Convert.ToString(reader[ConstantUtility.ThumbName]); } if (reader[ConstantUtility.Exe] != DBNull.Value) { objFileDetails.Extension = Convert.ToString(reader[ConstantUtility.Exe]); } } } } } } catch (Exception ex) { //Log the error ErrorUtility.WriteError(ex); } return(objFileDetails); }
public IActionResult Login(LoginModel loginModel) { LoginResponse loginResponse = _accountService.Login(loginModel); if (loginResponse == null) { return(ErrorUtility.BadRequest("Invalid Credentials")); } return(Ok(loginResponse)); }
public static IActionResult CreateErrorResult(HttpRequestMessage request, Exception ex) { HttpResponseMessage response = request.CreateResponse(HttpStatusCode.InternalServerError, new ApiResponse { ApiStatusCode = ErrorUtility.Parse((ex.InnerException ?? ex).Message), ApiStatusMessage = ErrorUtility.GetMessage((ex.InnerException ?? ex).Message), ExceptionDetails = new ApiExceptionDetails(ex) }); return(new ResponseMessageResult(response)); }
public UsersModel GetUsersByLdapLogin(string name, HttpContext httpContext, out List <SQLErrorModel> lstErrorMessages) { lstErrorMessages = null; string domaine = configuration.GetSection("Users")["Domaine"]; string ldap_login = name.Replace(domaine, ""); UsersModel ObjMaster = new UsersModel(); using (SqlConnection con = new SqlConnection(connectionString)) { ldap_login = "******" + ldap_login + "%"; string sql = "SELECT * FROM dbo.users where ldap_login like @ldap_login"; string parameters = "@ldap_login NVARCHAR(200)"; SqlCommand cmd = new SqlCommand("sp_executesql", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@stmt", sql); cmd.Parameters.AddWithValue("@params", parameters); cmd.Parameters.AddWithValue("@ldap_login", ldap_login); try { con.Open(); SqlDataReader rsVS = cmd.ExecuteReader(); while (rsVS.Read()) { ObjMaster.id = Convert.ToInt32(rsVS["id"]); ObjMaster.tri = rsVS["tri"].ToString(); ObjMaster.name = rsVS["name"].ToString(); ObjMaster.firstName = rsVS["firstName"].ToString(); ObjMaster.email = rsVS["email"].ToString(); ObjMaster.username = rsVS["username"].ToString(); ObjMaster.user_service = Convert.ToInt32(rsVS["user_service"]); ObjMaster.ldap_login = rsVS["ldap_login"].ToString(); } httpContext.Items[UsersKey] = ObjMaster; } catch (SqlException ex) //when (ex.Number == 50000) { lstErrorMessages = ErrorUtility.GetListError(ex, "UsersDataAccessLayer.GetUsersByLdapLogin().Sql"); } catch (Exception ex) { //ExceptionUtility.SendErrorToMail(ex, Global.ExceptionCaughtIn + "UsersDataAccessLayer.GetUsersByLdapLogin()"); } finally { con.Close(); } } return(ObjMaster); }
private static void ApplicationOnThreadException(object sender, ThreadExceptionEventArgs e) { LogService = new FileLogService(typeof(Program)); LogService.Error(e.Exception.Message); LogService.Info(e.Exception.StackTrace); ErrorUtility.DisplayOptionsButton = false; ErrorUtility.EnableSendMail = false; ErrorUtility.EnableWriteLog = false; ErrorUtility.Exception = e.Exception; ErrorUtility.Form = null; ErrorUtility.ShowError(); }
public async Task Consume(ConsumeContext <ICustomerCreateEvent> context) { try { _logger.LogInformation($"Customer Request received for order ref: {context.Message.CorrelationId}"); var customer = GetCustomerObject(context.Message); var checkCustomer = (await _customerRepository.FindByConditionAsync(c => c.EmailAddress == context.Message.EmailAddress)).ToList(); if (!checkCustomer.Any()) { _customerRepository.Add(customer); } else { _customerRepository.Update(checkCustomer.Single().UpdatePersonalDetails(customer)); } await _customerRepository.UnitOfWork.SaveEntitiesAsync(); _logger.LogInformation($"Customer Request saved successfully for order ref: {context.Message.CorrelationId}"); var result = (await _customerRepository.FindByConditionAsync(c => c.EmailAddress == context.Message.EmailAddress)).Single(); int cardDetailId = 0; if (context.Message.CardDetails is not null) { cardDetailId = result.CardDetails.First(x => x.CardNumberUnFormatted == context.Message.CardDetails.CardNumber).Id; } await context.RespondAsync <ICustomerCreatedEvent>(new CustomerCreatedEvent { CorrelationId = context.Message.CorrelationId, CustomerId = result.Id, CardDetailId = cardDetailId }); } catch (Exception ex) { _logger.LogError($"Customer process failed for order ref: {context.Message.CorrelationId} with error: {ErrorUtility.BuildExceptionDetail(ex)}"); await context.RespondAsync <IOrderProcessingFailedEvent>(new OrderProcessingFailedEvent { OrderRef = context.Message.CorrelationId, ErrorMessage = ErrorUtility.BuildExceptionDetail(ex) }); } }
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e) { var ex = (Exception)e.ExceptionObject; LogService = new FileLogService(typeof(Program)); LogService.Error(ex.Message); LogService.Info(ex.StackTrace); ErrorUtility.DisplayOptionsButton = false; ErrorUtility.EnableSendMail = false; ErrorUtility.EnableWriteLog = false; ErrorUtility.Exception = ex; ErrorUtility.Form = null; ErrorUtility.ShowError(); }
public async Task Consume(ConsumeContext <IOrderCreateEvent> context) { try { _logger.LogInformation($"Order create request received for order ref: {context.Message.OrderRef}"); var orderItems = context.Message.OrderItems.Select(item => new OrderItemEntry(item.ProductRef, item.ProductName, item.Quantity, item.Price)).ToList(); var order = new Order( context.Message.OrderRef , context.Message.PaymentId , context.Message.CustomerId , new Address( context.Message.DeliveryAddress.Street , context.Message.DeliveryAddress.City , context.Message.DeliveryAddress.Country , context.Message.DeliveryAddress.PostCode) , orderItems); _orderRepository.Add(order); await _orderRepository.UnitOfWork.SaveEntitiesAsync(); _logger.LogInformation($"Order request saved for order ref: {context.Message.OrderRef}"); var result = (await _orderRepository.FindByConditionAsync(or => or.OrderRef == context.Message.OrderRef)).Single(); var customer = (await _customerRepository.FindByConditionAsync(cs => cs.Id == context.Message.CustomerId)).Single(); await context.RespondAsync <IOrderCreatedEvent>(new OrderCreatedEvent { OrderId = result.Id, OrderRef = context.Message.OrderRef, CustomerEmail = customer.EmailAddress, CustomerName = customer.GetFullName }); } catch (Exception ex) { _logger.LogError($"Customer process failed for order ref: {context.Message.OrderRef} with error: {ErrorUtility.BuildExceptionDetail(ex)}"); await context.RespondAsync <IOrderProcessingFailedEvent>(new OrderProcessingFailedEvent { OrderRef = context.Message.OrderRef, ErrorMessage = ErrorUtility.BuildExceptionDetail(ex) }); } }
public async Task Consume(ConsumeContext <IUpdateBasketEvent> context) { try { var basket = (await _basketRepository.FindByConditionAsync(b => b.BasketRef == context.Message.BasketRef)).Single(); basket.AddBasketItem( context.Message.ProductId , context.Message.Quantity , context.Message.ProductPrice); _basketRepository.Update(basket); _logger.LogInformation($"Basket ref: {context.Message.BasketRef} is about to update"); await _basketRepository.UnitOfWork.SaveEntitiesAsync(); var basketResult = (await _basketRepository.FindByConditionAsync(bk => bk.BasketRef == context.Message.BasketRef)).Single(); var basketItems = new List <JsonBasketItem>(); foreach (var item in basketResult.BasketItems) { var product = (await _productRepository.FindByConditionAsync(p => p.Id == item.GetProductId)).Single(); basketItems.Add(new JsonBasketItem { Quantity = item.Quantity, Price = item.Amount, ProductName = product.Name, ProductRef = product.ProductRef }); } await context.RespondAsync <IBasketPlacedSuccessfullyEvent>( new BasketPlacedSuccessfullyEvent(context.Message.BasketRef, basketResult.GetTotal, basketItems)); _logger.LogInformation($"Basket ref: {context.Message.BasketRef} is updated & notified"); } catch (Exception ex) { _logger.LogInformation($"Basket ref: {context.Message.BasketRef} process failed with error {ErrorUtility.BuildExceptionDetail(ex)}"); await context.RespondAsync <IBasketProcessFailedEvent>( new BasketProcessFailedEvent(context.Message.BasketRef , ErrorUtility.BuildExceptionDetail(ex))); } }
/// <summary> /// For saving the details of the files that are uploaded by the user to the server /// </summary> /// <param name="originalFileNames">Name of the file that is to be uploaded</param> /// <param name="savedFileNames">Original name of the file followed by the Guid</param> /// <param name="userHashCode">unique user id.</param> /// <param name="machineName">Name of the machine used</param> /// <param name="ipAddress">IP address of the machine used</param> /// <param name="fileSize">total size of the file</param> /// <param name="extension">extension of the file being uploaded</param> /// <param name="thumbFileName">thumbnail image's name</param> /// <returns>file id of the file uploaded</returns> public int SaveFileDetails(string originalFileNames, string savedFileNames, string userHashCode, string machineName, string ipAddress, double fileSize, string extension, string thumbFileName) { int fileId = 0; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.SaveFileDetail, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding all parameters command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.OriginalFileName, originalFileNames)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SavedFileName, savedFileNames)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.UserHashCode, userHashCode)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.MachineName, machineName)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.IpAddress, ipAddress)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileSize, fileSize)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.Extension, extension)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.ThumbFileName, thumbFileName)); dbConnection.Open(); //Get the file id. var result = command.ExecuteScalar(); if (result != null) { int.TryParse(Convert.ToString(result), out fileId); } } } } } catch (SqlException ex) { //log the error ErrorUtility.WriteError(ex); } return(fileId); }
/// <summary> /// Saves the user details and returns the hashcode /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="email"></param> /// <param name="password"></param> /// <returns></returns> public bool SaveUserDetails(string firstName, string lastName, string email, string password) { bool isSuccess = false; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.SaveUserDetail, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FirstName, firstName)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.LastName, lastName)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.Email, email)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.Password, password)); dbConnection.Open(); //Get the number of row affected. var result = command.ExecuteScalar(); int recordsAffected = 0; if (result != null) { if (int.TryParse(result.ToString(), out recordsAffected) && recordsAffected > 0) { isSuccess = true; } } } } } } catch (SqlException ex) { //log the error ErrorUtility.WriteError(ex); } return(isSuccess); }
public void Execute() { Console.WriteLine("Delete Started."); try { //fetch all the resources to be uploaded AssetDataFactory _dataFactory = new AssetDataFactory(); S3Uploader cdnManager = new S3Uploader(); Console.WriteLine("Please specify the relative path in bucket which need to be deleted"); Console.WriteLine(bucketName); string inputRelativePath = Console.ReadLine(); client = new AmazonS3Client(bucketRegion); ListingObjectsAsync(inputRelativePath).Wait(); } catch (Exception e) { ErrorUtility.LogError(e, GartnerApplication.Unknown, string.Format("Error: Upload Doc error: " + e.Message)); } }
/// <summary> /// gets all the files uploaded by the user. /// </summary> /// <param name="userHashCode">unique user Id</param> /// <param name="isAdmin"></param> /// <param name="isSearchable"></param> /// <param name="searchTerm"></param> /// <returns>original name and saved name of the files uploaded by the user.</returns> public DataTable GetAllFiles(string userHashCode, int isAdmin, int isSearchable, string searchTerm) { DataTable fileNames = new DataTable(); try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetFileDetails, connection)) { connection.Open(); command.CommandType = CommandType.StoredProcedure; // Adding parameters command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.UserHashCode, userHashCode)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.IsAdmin, isAdmin)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.IsSearchable, isSearchable)); if (!string.IsNullOrEmpty(searchTerm)) { command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SearchTerm, searchTerm)); } using (SqlDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { fileNames.Load(reader); } } } } } } catch (Exception ex) { ErrorUtility.WriteError(ex); } return(fileNames); }
/// <summary> /// Returns all the files for the admin /// </summary> /// <param name="userId">Id of the user if all the files are to be loaded then Id is passed as 0</param> /// <param name="searchField">Optional parameter will be null if all the files are to be loaded</param> /// <param name="searchOper">the search operation to be done</param> /// <param name="searchString">The term to be searched for</param> /// <returns>list of files and details satisfying the condition</returns> public DataTable GetAllFilesForAdmin(int userId, string searchField, string searchOper, string searchString) { DataTable allFileDetails = new DataTable(); try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetAllFilesForAdmin, connection)) { connection.Open(); command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.UserId, userId)); if (!string.IsNullOrEmpty(searchField)) { command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SearchField, searchField)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SearchOper, searchOper)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.SearchString, searchString)); } using (SqlDataAdapter adapter = new SqlDataAdapter()) { adapter.SelectCommand = command; adapter.Fill(allFileDetails); } } } } } catch (SqlException ex) { //Log the error ErrorUtility.WriteError(ex); } return(allFileDetails); }
/// <summary> /// Deletes the particular file from db /// </summary> /// <param name="fileId">Unique file Id of the file to be deleted</param> /// <param name="isAdmin">whether the user is admin or not.</param> /// <returns>returns whether the update was successful or not</returns> public bool DeleteFile(int fileId, bool isAdmin) { bool isSuccess = false; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.DeleteFile, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.IsAdmin, isAdmin)); dbConnection.Open(); var result = command.ExecuteScalar(); int recordsAffected = 0; if (result != null) { if (int.TryParse(result.ToString(), out recordsAffected) && recordsAffected > 0) { isSuccess = true; } } } } } } catch (Exception ex) { //Log the error ErrorUtility.WriteError(ex); } return(isSuccess); }
/// <summary> /// gets the number of file uploaded and downloaded /// by the user. /// </summary> /// <param name="userHashCode">Unique user code</param> public UserAccount GetAccountDetails(string userHashCode) { UserAccount objAccDetails = null; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetAccountDetails, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.UserHashCode, userHashCode)); dbConnection.Open(); SqlDataReader reader = command.ExecuteReader(); //Read data using datareader if (reader.HasRows && reader.Read()) { objAccDetails = new UserAccount(); objAccDetails.TotalFiles = Convert.ToString(reader[ConstantUtility.TotalFiles]); objAccDetails.TotalDownloads = Convert.ToString(reader[ConstantUtility.TotalDownloads]); objAccDetails.TotalSize = Convert.ToString(reader[ConstantUtility.TotalSize]); } } } } } catch (Exception ex) { //Log the error ErrorUtility.WriteError(ex); } return(objAccDetails); }
/// <summary> /// Gets the user details using hashcode /// </summary> /// <param name="userHashCode">user's unique hashcode</param> /// <returns></returns> public User GetUserByHashCode(string userHashCode) { User objUser = null; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetUserDetailsByHashCode, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.UserHashCode, userHashCode)); dbConnection.Open(); SqlDataReader reader = command.ExecuteReader(); //Read data using datareader if (reader.HasRows && reader.Read()) { objUser = new User(); objUser.EmailId = Convert.ToString(reader[ConstantUtility.Email]); objUser.IsAdmin = Convert.ToBoolean(reader[ConstantUtility.IsAdmin]); objUser.UserName = Convert.ToString(reader[ConstantUtility.UserName]); objUser.UserHashCode = userHashCode; } } } } } catch (Exception ex) { ErrorUtility.WriteError(ex); } return(objUser); }
/// <summary> /// Gets the password of the locked file /// </summary> /// <param name="fileId">Id of the file</param> /// <returns></returns> public string GetFilePassword(int fileId) { string filePassword = string.Empty; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetFilePassword, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); dbConnection.Open(); SqlDataReader reader = command.ExecuteReader(); //Read data using datareader if (reader.HasRows && reader.Read()) { if (reader[ConstantUtility.FilePassword] != DBNull.Value) { filePassword = Convert.ToString(reader[ConstantUtility.FilePassword]); } } } } } } catch (Exception ex) { //Log the error ErrorUtility.WriteError(ex); } return(filePassword); }
/// <summary> /// Resets the password of the current user. /// </summary> /// <param name="userHashCode">Unique user hashcode.</param> /// <param name="currentPassword">Existing password</param> /// <param name="newPassword">new password</param> /// <returns></returns> public bool ResetPassword(string userHashCode, string currentPassword, string newPassword) { bool isReset = false; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.ResetPassword, dbConnection)) { command.CommandType = CommandType.StoredProcedure; //Adding parameter command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.UserHashCode, userHashCode)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.CurrentPassword, currentPassword)); command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.NewPassword, newPassword)); dbConnection.Open(); var status = command.ExecuteScalar(); if (status != null) { bool.TryParse(status.ToString(), out isReset); } } } } } catch (SqlException ex) { //log the error ErrorUtility.WriteError(ex); } return(isReset); }
/// <summary> /// /// </summary> /// <param name="fileId"></param> /// <returns></returns> public DataTable GetFileOwnerAndDownloadHistory(int fileId) { DataTable dt = new DataTable();; try { if (!string.IsNullOrEmpty(ConnectionString)) { using (SqlConnection dbConnection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(ConstantUtility.StoredProcedures.GetFileOwnerAndDownloadHistory, dbConnection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter(ConstantUtility.StoredProcedureParams.FileId, fileId)); dbConnection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { dt.Load(reader); } } // ds = command.ExecuteNonQuery(); //dt.Load(command.ExecuteReader(),LoadOption.OverwriteChanges); } } } } catch (Exception ex) { ErrorUtility.WriteError(ex); dt = null; } return(dt); }