Translate

Home > 2021

2021

ASP.NET GridView TimeSpan 24 hour to AM PM

Thursday, December 2, 2021 Category : 0

 <asp:TemplateField HeaderText="IN_TIME">
                                            <ItemTemplate>
                                                <asp:Label ID="lblInTime" runat="server" Text='<%# new DateTime().Add(TimeSpan.Parse(Eval("IN_TIME").ToString())).ToString("hh:mm tt") %>' />
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField HeaderText="OUT_TIME">
                                            <ItemTemplate>
                                                <asp:Label ID="lblOUTTime" runat="server" Text='<%# new DateTime().Add(TimeSpan.Parse(Eval("OUT_TIME").ToString())).ToString("hh:mm tt") %>' />
                                            </ItemTemplate>
                                        </asp:TemplateField>

Angular Download File from server , C# Rest Api

Thursday, September 9, 2021 Category : , 0

 HTML

 

<div class="input-group-append">
       <button type="button" class="btn btn-primary"
           (click)="downloadButtonClick('inputGroupFile03')">
            <i class="fas fa-download"> </i>
             Download</button>
 </div>

 

  Type Script


  downloadButtonClick(fileNamestring) {


  
    let binaryDataany = [];

    this.http.get(this.env.apiUrl + 'api/Supplier/get_doc_details_by_id2?id=' + this.model.SupID , { responseType: "blob" }).subscribe(data => {

      binaryData.push(data);

      let dataType = data.type;
      let downloadLink = document.createElement('a');
      downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: dataType }));

        downloadLink.setAttribute('download', "File Name.ext");
   

      document.body.appendChild(downloadLink);
      downloadLink.click();



    }, error => {
      console.error(error)
      this.alertService.error(error);
    });




  }

Web Api
 
 
[Authorize(Policy = nameof(Policy.Account))]
[HttpGet("get_doc_details_by_id2")]
public ActionResult GetDocDetailsById2(string id)
{
try
{

var data = _shopService.FindDocumentById(id);
                 if(
data != null) {
                     string fileType_ = "application/octet-stream";
if (data.fileName.ToLower().Contains("pdf"))
{
fileType_ = "application/pdf";
}
return File(data.fileByteArray, fileType_ , data.filename);
                 }
 
                return NotFound();
}
catch (Exception ex)
{
return StatusCode(500, ex.Message + ex.StackTrace);
}

C# AWS SNS Subscribtion configuration

Wednesday, September 1, 2021 Category : 1

Install Nuget Dependency

 

 

public class Messages
    {
        public string Type { get; set; }
        public string MessageId { get; set; }
        public string Token { get; set; }
        public string TopicArn { get; set; }
        public object Message { get; set; }
        //public Message Message2 { get; set; }
        public string SubscribeURL { get; set; }
        public string Timestamp { get; set; }
        public string SignatureVersion { get; set; }
        public string Signature { get; set; }
        public string SigningCertURL { get; set; }
        public string Subject { get; set; }
        public string UnsubscribeURL { get; set; }
    }

 

     [Route("api/awssns")]
    [ApiController]
    public class ValuesController : ControllerBase
    {

        private readonly ILogger<ValuesController> _logger;

        public ValuesController(ILogger<ValuesController> logger)
        {
            _logger = logger;
        }

       

        [HttpPost("[action]")]
        public async Task<IActionResult> webhook()
        {

            var re = Request;
            var headers = re.Headers;
            string body = "";
            try
            {

                string messagetype = Request.Headers["x-amz-sns-message-type"];
                //if (headers.Contains("Custom"))
                //{
                //    string token = headers.TryGetValue("Custom").First();
                //}
                //Logger.Debug(messagetype);

                _logger.LogInformation("**** MSDSL BEGIN LOG ****");
                _logger.LogInformation(messagetype);


                //HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

                using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
                {
                     body = stream.ReadToEnd();
                    // body = "param=somevalue&param2=someothervalue"
                    _logger.LogInformation(body);


                    

                    Messages msg = JsonConvert.DeserializeObject<Messages>(body);

                    if (msg != null)
                    {
                        if (msg.SignatureVersion.Equals("1"))
                        {
                            //temp
                            {
                                var aws = Amazon.SimpleNotificationService.Util.Message.ParseMessage(body);
                                bool r = aws.IsMessageSignatureValid();
                                if (r)
                                {
                                    _logger.LogInformation("Signature verification succeeded");
                                }
                                else
                                {
                                 Message message = JsonConvert.DeserializeObject<Message>(msg.Message.ToString());
                                    _logger.LogInformation("Signature verification failed");
                                    await new LogManager().Insert(new Client_Log { Message = JsonConvert.SerializeObject(msg.Message), Response = body, Error = "Signature verification failed", timestamp = DateTime.Now }, message.merchantWallet);
                                    return BadRequest("Signature verification failed");
                                }
                            }
                            if (messagetype.Equals("Notification"))
                            {
                                _logger.LogInformation("Subject : " + msg.Subject);


                                 Message message = JsonConvert.DeserializeObject<Message>(msg.Message.ToString());
                                

// do what you want

                                                           }
                            else if (messagetype.Equals("SubscriptionConfirmation"))
                            {
                                 

                                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

                                var response = await client.GetAsync(msg.SubscribeURL);
                                response.EnsureSuccessStatusCode();
                            }
                            else if (messagetype.Equals("UnsubscribeConfirmation"))
                            {
                            
                                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

                                var response = await client.GetAsync(msg.UnsubscribeURL);
                                response.EnsureSuccessStatusCode();
                            }
                        }
                        else
                        {
                                 Message message = JsonConvert.DeserializeObject<Message>(msg.Message.ToString());
                            _logger.LogInformation("Unexpected signature version. Unable to verify signature.");
                                                     

                        }
                    }
                    else
                    {
                                        await new LogManager().Insert(new Client_Log { Response = body, Error = "Body Deserialize fail move to line 141", timestamp = DateTime.Now, Message = "" });

                    }

                }



                _logger.LogInformation("**** MSDSL END LOG ****");
            }
            catch (Exception ex)
            {
                _logger.LogError( ex,ex.Message);
                                return StatusCode(500,ex);
                               
            }

            return Ok();

        }

     
    }

 

Youtube Link

Angular File, Image data manipulation

Monday, March 8, 2021 Category : 0

 HTML

 

 <div class="col-md-6">

          <div class="col-md-12">
            <br>
            <br>
            <div class="form-group">
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text">NID Image</span>
                </div>
                <div class="custom-file">
                  <input type="file" class="custom-file-input" #file
                         name="imageFile" (change)="fileChange($event)"
                         id="inputGroupFile01"
                         >
                  <label class="custom-file-label" for="inputGroupFile01">{{FilePath}}</label>
                </div>
              </div>
            </div>

          </div>

          <div class="col-md-12">
            <div class="row">
                <div class="col-md-3">

                </div>

                <div class="col-md-6">
                  <div class="card" >
                    <div class="el-card-item">
                        <div class="el-card-avatar el-overlay-1"> 
                          <img [src]="nidImageData" alt="user" width="200" height="100">
                        </div>
                        <div class="el-card-content">
                            <br> 
                        </div>
                    </div>
                  </div>
                </div>

                <div class="col-md-3">

                </div>
            </div>
            
          </div>
 
 
 

 TypeScript

file: File
FilePath: string='Choose file';
nidImageData:string;

fileChange(event) {
  let fileList: FileList = event.target.files;
  if (fileList.length > 0{
    this.file = fileList[0];
    this.FilePath = this.file.name;
    //let fileSize: number = fileList[0].size;
    //if (fileSize <= 10485760) {
      
    //}
    //else {
    //  this.alertService.error("File size is exceeded");
    //}

    const reader = new FileReader();
    reader.readAsDataURL(this.file); // toBase64
    reader.onload = () => {
      this.nidImageData = reader.result as string; // base64 Image src
    };

  }
  else {
    this.alertService.error("Something went Wrong.");
    this.FilePath ='Choose file';
}
}  

 

  let formData: FormData = new FormData();
  formData.append('Document', this.file);

  this._http.post<Result>(this.env.apiUrl + url, formData).subscribe(result => {
    console.log(result);
    this.resultMaster = result;
    if (this.resultMaster.Status == true{
      console.log(this.resultMaster);
      // this.designationList = JSON.parse(this.resultMaster.Data);
      this._alertService.success('Data Saved Successfully');

      this._file.nativeElement.value = '';

      this.model = new ProductSetup();
      this.rerender();


    } else {
      this._alertService.error(this.resultMaster.Message);

      //window.scroll(0, 0);

    }

  }, error => {
    this._alertService.error(error);

    //window.scroll(0, 0);

  });

 

.NET CORE API

 

[Authorize(Policy = nameof(Policy.Account))]
        [HttpPost("create")]
        public ActionResult Create() //[FromBody] Supplier request
        {
            try
            {
                var DocumentMain = JsonConvert.DeserializeObject<Supplier>(Request.Form["DocumentMain"].ToString());
                var DocumentDoc = JsonConvert.DeserializeObject<SupplierDoc>(Request.Form["DocumentDoc"].ToString());

                if(Request.Form.Files.Count > 0)
                {
                    foreach(var d in Request.Form.Files)
                    {
                        IFormFile file = d;
                        switch (file.Name)
                        {
                            case "Document1":
                                using (var ms = new MemoryStream())
                                {
                                    file.CopyTo(ms);
                                    DocumentDoc.TradeFile = ms.ToArray();
                                    DocumentDoc.TradeFileType = file.FileName;
                                }
                                break;

...............

.....................

TSQL RaiseError from exception

Sunday, January 24, 2021 Category : 0

 
ALTER PROCEDURE [dbo].[usp_GetErrorInfo]  
AS  

DECLARE @ErrorNumber INT
SET @ErrorNumber=ERROR_NUMBER()

DECLARE @ErrorSeverity INT
SET @ErrorSeverity=ERROR_SEVERITY()

DECLARE @ErrorState INT
SET @ErrorState=ERROR_STATE()

DECLARE @ErrorLine INT
SET @ErrorLine=ERROR_LINE()

DECLARE @ErrorMessage NVARCHAR(max)
SET @ErrorMessage=ERROR_MESSAGE()

--SELECT  
    
--    ERROR_NUMBER() AS ErrorNumber  
--    ,ERROR_SEVERITY() AS ErrorSeverity  
--    ,ERROR_STATE() AS ErrorState  
--    ,ERROR_PROCEDURE() AS ErrorProcedure  
--    ,ERROR_LINE() AS ErrorLine  
--    ,ERROR_MESSAGE() AS ErrorMessage;  


RAISERROR (@ErrorMessage, -- Message text.  
               @ErrorSeverity, -- Severity.  
               @ErrorState -- State.  
               ); 

TSQL Table NONCLUSTERED Indexing example

Category : 0

 if index already exists then it will rebuild elase generate a new one.




IF NOT EXISTS (
SELECT *
FROM sys.indexes
WHERE name='IX_StyleSize' AND object_id = OBJECT_ID('dbo.StyleSize') )

BEGIN
        PRINT 'index not found stylesize'

        BEGIN TRY
           
       
               
        BEGIN TRANSACTION
       
        CREATE NONCLUSTERED INDEX IX_StyleSize ON dbo.StyleSize
            (
            GroupID,
            PrdID,
            BTID,
            CBTID,
            SSID,
            sBarcode,
            SupID
            ) WITH ( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
       
        ALTER TABLE dbo.StyleSize SET (LOCK_ESCALATION = TABLE)
    
        --COMMIT

        END TRY
        BEGIN catch
            IF @@TRANCOUNT > 0 
                ROLLBACK TRANSACTION; 
            EXECUTE usp_GetErrorInfo; 
        END CATCH
        
        IF @@TRANCOUNT > 0 
            COMMIT TRANSACTION;

END
ELSE
BEGIN

    BEGIN TRY
       
        PRINT 'index found on stylesize rebuilding...'

        BEGIN TRANSACTION
            ALTER INDEX ALL ON dbo.StyleSize REBUILD;
        COMMIT TRANSACTION


        PRINT 'stylesize index rebuild successfull....'   
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 
            ROLLBACK TRANSACTION; 
        --EXECUTE usp_GetErrorInfo; 
        EXEC usp_GetErrorInfo
    END CATCH
    
END


Powered by Blogger.