Saturday, April 20, 2024

Upload file to Digital Ocean space using .net

 

When user choose any file from local HD [in the second textbox], or put any external URL in the first textbox, a callback event will run and upload this file to Azure blob and put the short link in the first textbox to save to database as varchar[200]

OnChange in Javascript call C# API method that can accept File or URL








<form asp-action="Create">
		<div class="form-group position-relative">
			<label asp-for="Image" class="control-label"></label>
			<input asp-for="Image" class="form-control" id="ximage-form" />
			<span asp-validation-for="Image" class="text-danger"></span>
			<div class="input-group mb-3 custom-file-with-url">
				<div class="custom-file">
					<input type="file" class="custom-file-input" id="ximage-file" aria-describedby="inputGroupFileAddon01" accept="image/*" >
					<label class="custom-file-label" for="ximage-file"></label>
				</div>
			</div>
			<div class="row">
				<img id="xloading-img" class="d-none mx-auto" src="~/assets/images/loading.gif" alt="" />
			</div>
		</div>
		<div class="form-group">
			<input id="submit-btn" type="submit" value="Create" class="btn btn-primary" />
		</div>
</form>


<script>
	function isImage(url) {
	  return /^https?:\/\/.+\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url);
	}

    $(document).ready(function () {
        $("#ximage-form").change(function () {
				var file = $("#ximage-form").val();
                console.log(file);

                if (!(isImage(file))) {
                    alert("It is not a image. Please choose a image format file to upload.");
                    return;
                }

                const fd = new FormData();

                fd.append("URL", file);
                $("#submit-btn").addClass("d-none");
                $("#xloading-img").removeClass("d-none");
                $.ajax({
                    url: "/FileUpload/Upload",
                    enctype: 'multipart/form-data',
                    method: "PUT",
                    processData: false,
                    contentType: false,
                    cache: false,
                    data: fd,
                    success: function (data) {
                        $("#ximage-form").val(data);
                        $("#submit-btn").removeClass("d-none");
                        $("#xloading-img").addClass("d-none");
                    }
                });

            
        });
    });
</script>

<script>
    $(document).ready(function () {
        $("#ximage-file").change(function () {
            const files = [...document.querySelector('#ximage-file').files];
            files.forEach(file => {
                console.log(file);

                if (!file.type.match("image/")) {
                    alert(file.name + " is not a image. Please choose a image format file to upload.");
                    console.log(file.type);
                    return;
                }

                const fd = new FormData();

                fd.append("File2Upload", file);
                $("#submit-btn").addClass("d-none");
                $("#xloading-img").removeClass("d-none");
                $.ajax({
                    url: "/FileUpload/Upload",
                    enctype: 'multipart/form-data',
                    method: "POST",
                    processData: false,
                    contentType: false,
                    cache: false,
                    data: fd,
                    success: function (data) {
                        $("#ximage-form").val(data);
                        $("#submit-btn").removeClass("d-none");
                        $("#xloading-img").addClass("d-none");
                    }
                });

            });
        });
    });
</script>




using Microsoft.AspNetCore.Mvc;
using Amazon.S3;
using Amazon.S3.Transfer;

namespace ArabAuthorsIndex.Controllers
{
    public class FileUploadController : Controller
    {
        [HttpPost]
        public async Task<string> Upload([FromForm] IFormFile File2Upload, [FromForm] string Name)
        {
            if (File2Upload == null) return "";

            string fileName = string.IsNullOrEmpty(Name) ? $"{DateTime.Now.Ticks}-{File2Upload.FileName.Replace(" ", "-")}" : Name;

            var newMemoryStream = new MemoryStream();
            File2Upload.CopyTo(newMemoryStream);


            var s3ClientConfig = new AmazonS3Config
            {
                ServiceURL = "https://sgp1.digitaloceanspaces.com"
            };
            IAmazonS3 s3Client = new AmazonS3Client(AccessKey, SecretKey, s3ClientConfig);
            try
            {
                var fileTransferUtility = new TransferUtility(s3Client);
                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = "ddl-temp" ,
                    InputStream = newMemoryStream,
                    StorageClass = S3StorageClass.StandardInfrequentAccess,
                    PartSize = 6291456, // 6 MB
                    Key = fileName,
                    CannedACL = S3CannedACL.PublicRead
                };
                fileTransferUtility.Upload(fileTransferUtilityRequest);
                return $"https://ddl-temp.sgp1.digitaloceanspaces.com/{fileName}";
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                if (e.Message.Contains("disposed"))
                    return "";
            }
            return "";
        }



        [HttpPut]
        public async Task<string> Upload(string URL, string Name)
        {
            try
            {
                if (URL == null) return "";

                Uri fileURL = new Uri(URL);
                var fileName = fileURL.Segments.Last();

                fileName = string.IsNullOrEmpty(Name) ? $"{DateTime.Now.Ticks}-{fileName.Replace(" ", "-")}" : Name;

                // Download the file from the URL and upload it to S3
                using (var httpClient = new HttpClient())
                {
                    using (var response = await httpClient.GetAsync(fileURL))
                    {
                        if (!response.IsSuccessStatusCode)
                        {
                            return URL; // Handle download errors
                        }

                        using (var newMemoryStream = await response.Content.ReadAsStreamAsync())
                        {

                            var s3ClientConfig = new AmazonS3Config
                            {
                                ServiceURL = "https://sgp1.digitaloceanspaces.com"
                            };
                            IAmazonS3 s3Client = new AmazonS3Client(AccessKey, SecretKey, s3ClientConfig);
                            try
                            {
                                var fileTransferUtility = new TransferUtility(s3Client);
                                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                                {
                                    BucketName = "ddl-temp",
                                    InputStream = newMemoryStream,
                                    StorageClass = S3StorageClass.StandardInfrequentAccess,
                                    PartSize = 6291456, // 6 MB
                                    Key = fileName,
                                    CannedACL = S3CannedACL.PublicRead
                                };
                                fileTransferUtility.Upload(fileTransferUtilityRequest);
                                return $"https://ddl-temp.sgp1.digitaloceanspaces.com/{fileName}";
                            }
                            catch (AmazonS3Exception e)
                            {
                                Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
                                if (e.Message.Contains("disposed"))
                                    return "";
                            }


                        }
                    }
                }

                return $"https://ddl-temp.sgp1.digitaloceanspaces.com/{fileName}";
            }
            catch (Exception ex)
            {
                return "";
            }
        }

    }
}



//Notes

Install the AWS SDK:

  • Make sure you have the AWS SDK for .NET (AWSSDK.S3) installed in your project. You can use NuGet Package Manager to install it.

Wednesday, March 6, 2024

Software Design Documents

 Software Design Documents

  1. Technical Architecture Design Document (TADD)
  2. Solution High-Level Design Document (HLD)
  3. Solution Low-Level Design Document (LLD)
  4. Functional Design Document (FDD)
  5. Business Requirement Document (BRD)
  6.  Software Requirements Specification (SRS) 

1. Technical Architecture Design Document (TADD):
    - Purpose: The TADD outlines the high-level technical architecture for a system or solution. It provides a blueprint for how different components will interact, including hardware, software, networks, and databases.
    - Contents:
        - System Components: Describes the major building blocks of the system.
        - Interfaces: Specifies how different components communicate.
        - Security Considerations: Addresses security measures.
        - Scalability and Performance: Discusses system scalability and performance requirements.
        - Deployment Diagrams: Illustrates the deployment of components.
    - Audience: Typically read by technical architects, developers, and infrastructure teams.
    - Example: Imagine it as the architectural blueprint for constructing a house.

2. Solution High-Level Design (HLD) Document:
    - Purpose: The HLD provides a big-picture view of the system. It outlines the functional aspects of various modules and their interactions.
    - Contents:
        - Module Descriptions: Explains the purpose and functionality of each module.
        - Data Flow Diagrams: Illustrates data flow between modules.
        - High-Level Logic: Describes the overall system logic.
        - Integration Points: Identifies interfaces with external systems.
    - Audience: Project managers, architects, and stakeholders.
    - Analogy: Think of it as an architectural sketch before detailed construction plans.

3. Solution Low-Level Design (LLD) Document:
    - Purpose: The LLD dives deeper into technical details. It provides instructions for developers on how to implement each module.
    - Contents:
        - Detailed Logic: Describes algorithms, data structures, and coding guidelines.
        - Database Schema: Specifies database tables, relationships, and queries.
        - Class Diagrams: Represents class hierarchies and relationships.
        - Code Snippets: Provides code examples.
    - Audience: Developers and testers.
    - Analogy: Similar to detailed construction blueprints for individual rooms in a house.

4. Functional Design Document (FDD):
    - Purpose: The FDD focuses on the functional requirements of the system. It translates business requirements into system features.
    - Contents:
        - Use Cases: Describes user interactions and system behavior.
        - User Interfaces: Illustrates screens, forms, and navigation.
        - Business Rules: Specifies rules governing system behavior.
        - Data Flow: Shows how data moves through the system.
    - Audience: Business analysts, designers, and developers.
    - Comparison: Like designing the layout and features of rooms in a house.

5. Business Requirement Document (BRD):
    - Purpose: The BRD captures high-level business needs and objectives. It serves as a foundation for subsequent design and development.
    - Contents:
        - Business Goals: States the purpose of the project.
        - Scope: Defines what's in and out of scope.
        - Stakeholder Requirements: Gathers input from various stakeholders.
        - Constraints and Assumptions: Lists limitations and assumptions.
    - Audience: Business stakeholders, project managers, and sponsors.
    - Analogy: Similar to the initial client brief for building a house.

6. A Software Requirements Specification (SRS) 
is a comprehensive document that outlines the requirements for developing a software system. Let's break down its key aspects:

   Purpose of the Document: SRS serves as a blueprint for the software development process.
    - It describes what the software will do and how it is expected to perform.
    - Both functional and non-functional requirements are captured in this document.

   Contents of an SRS:
    - Introduction:
        - Explains the purpose of the document and its significance.
        - Describes the scope, development cost, and time required.
    - General Description:
        - Outlines the product's functions, user objectives, features, and benefits.
        - Highlights the importance of the product and its relevance to user communities.
    - Functional Requirements:
        - Specifies the expected behavior of the system.
        - Ranks functional requirements, including calculations and data processing.
        - Describes the relationship between input and output.
    - Interface Requirements:
        - Details how the software communicates with other programs or users.
        - Covers languages, codes, messages, and interactions.
    - Performance Requirements:
        - Addresses system performance expectations, such as response time and throughput.
    - Design Constraints:
        - Lists any limitations or constraints affecting the software design.
    - Non-Functional Attributes:
        - Includes quality attributes like reliability, usability, and security.
    - Preliminary Schedule and Budget:
        - Provides an overview of the development timeline and estimated costs.
    - Appendices:
        - Contains additional relevant information.
    - Uses of SRS Document:
        - Ensures alignment among development teams.
        - Acts as a single source of truth for all stakeholders.
        - Facilitates decision-making throughout the product lifecycle.

   Why Use an SRS Document?:
    - Provides a complete project picture.
    - Keeps all teams on the same page.
    - Helps meet each requirement and make informed decisions.
    - Ultimately contributes to successful software development.



In addition to the documents we discussed earlier, there are several other essential documents in the software development process. Let's explore them:

1. Installation Guide:
    - Provides step-by-step instructions for installing and configuring the software.
    - Helps users set up the system correctly.

2. Code of Conduct:
    - Defines guidelines for behavior within the development team.
    - Promotes a positive and respectful work environment.

3. API Documentation (Postman Collection):
    - Describes how to use APIs (Application Programming Interfaces).
    - Includes details on endpoints, request methods, and response formats.

4. Knowledge Base Documentation:
    - Contains articles, FAQs, and troubleshooting guides.
    - Helps users find solutions to common issues.

5. Troubleshooting Documentation:
    - Provides guidance on identifying and resolving software problems.
    - Helps support teams assist users effectively.

6. Release Notes:
    - Summarizes changes, enhancements, and bug fixes in each software release.
    - Keeps users informed about new features.

7. Software Architecture Diagram:
    - Illustrates the system's high-level structure and components.
    - Helps developers understand the overall design.

8. Recommended Technical Articles:
    - Curated resources for developers.
    - Includes best practices, design patterns, and optimization techniques.

9. Most Used Database Queries:
    - Lists common SQL queries for database interactions.
    - Useful for developers and database administrators.

Remember, thorough documentation ensures smooth collaboration, efficient development, and successful software deployment!

Thursday, January 11, 2024

How to send SMS in C# using Unifonic

 How to send SMS in C# using Unifonic?


        public static async Task UniFonicSendConfirmVisitSMSAsync(string mobile)
{ try { using (var httpClient = new HttpClient()) { var url = "https://el.cloud.unifonic.com/rest/SMS/messages"; var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("AppSid", "******************"), new KeyValuePair<string, string>("SenderID", "xxx"), new KeyValuePair<string, string>("Body", "xxxxxxxxxxxxxxxxxxxxxx"), new KeyValuePair<string, string>("Recipient", mobile), new KeyValuePair<string, string>("responseType", "JSON"), new KeyValuePair<string, string>("CorrelationID", UniqueID), new KeyValuePair<string, string>("baseEncode", "true"), new KeyValuePair<string, string>("MessageType", "6"), new KeyValuePair<string, string>("statusCallback", "sent"), new KeyValuePair<string, string>("async", "false") }); var response = await httpClient.PostAsync(url, formContent); if (response.IsSuccessStatusCode) { Console.WriteLine("SMS sent successfully."); } else { Console.WriteLine("Failed to send SMS."); } } } catch { // $"Please enter a valid phone number. Current Phone number is {patient.mobile}."; } }