Translate

AngularJs ASP.NET WepApi File Upload

Sunday, November 1, 2020 Category : , 0

 AngularJs Code:


 var formData = new FormData();
      
        formData.append('files', data);
        formData.append('fileName', data.name);

        return $http({
            url: _urlBase + 'api/app/CustomerExcelUpload',
            method: 'POST',
            //data: JSON.stringify(data),
            processData: false,
            contentType: false,
            data: (formData),
            headers: { 'content-type': undefined, 'Authorization': username + ':' + password }
                    //, transformRequest: angular.identity
            });



ASP.NET WebApi (4.5)


  [HttpPost]
        [Route("api/app/CustomerExcelUpload")]
        public async Task<IHttpActionResult> CustomerExcelUpload()
        {
            //HttpResponseMessage result = null;
            ResponseObj responsobj = new ResponseObj();
            responsobj.COUNT = 0;
            responsobj.CODE = 0;

            try
            {
                

                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["files"];
                    var httpFileName = HttpContext.Current.Request.Form["fileName"];

                    if (httpPostedFile != null)
                    {
                        // Validate the uploaded image(optional)

                        // Get the complete file path
                        var fileSavePath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/upload_doc"), httpPostedFile.FileName);

                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }

                responsobj.Message = "OK";
                responsobj.Success = true;
                responsobj.CODE = 0;
                return Content(HttpStatusCode.OK, responsobj);

            }
            catch (Exception ex)
            {
                Log.Debug("Bad Request");
                responsobj.Message = ex.Message;
                responsobj.Success = false;
                responsobj.CODE = 2;
                return Content(HttpStatusCode.OK, responsobj);

            }
        }



<system.web>
  <httpRuntime executionTimeout="240000" maxRequestLength="2147483647" />
</system.web>

<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="4294967295"/>
  </requestFiltering>
</security>

ASP.NET C# File Download

Saturday, July 18, 2020 Category : 0

HttpContext.Current.Response.ContentType = "application/x-download";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=RosterFormat.xlsx");
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.WriteFile(path);
                HttpContext.Current.Response.End();

SQL Date Loop For Each Month

Thursday, July 2, 2020 Category : 0


 DECLARE @FromDate DATETIME
 SET @FromDate='01/01/2020'

 DECLARE @ToDate DATETIME
 SET @ToDate= CONVERT(DATETIME, CAST(  DATEPART(MONTH,GETDATE()) AS NVARCHAR(50) ) + '/01/' + CAST( DATEPART(YEAR,GETDATE()) AS NVARCHAR(50)) ,101 )

 DECLARE @TableName NVARCHAR(50)

 WHILE (@FromDate <= @ToDate)
 BEGIN

     SET @TableName = 'Sales'+ CAST( DATEPART(YEAR,@FromDate) AS NVARCHAR(50)) + RIGHT('00'+ISNULL( CAST( DATEPART(MONTH,@FromDate) AS NVARCHAR(50)) ,''),2)
     PRINT @TableName

     SET @FromDate = DATEADD(MONTH,1,@FromDate)
 END

The target "GatherAllFilesToPublish" does not exist in the project.

Sunday, June 28, 2020 Category : , 0

I fixed the issue by doing following modifications to the Project file. have VS 2012 and the web application was MVC 4

1. Unload the project and start editing the csproj file.

2. Added following lines.

<PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
 </PropertyGroup>

3. Added following lines.(Note that some of the Import statments may already exisits. In such case you do not need to add them.

 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />



Source : https://forums.asp.net/t/1838524.aspx?The+target+GatherAllFilesToPublish+does+not+exist

Answer by :  dilanh

Angular DataTables Server side pagination & Sorting

Friday, November 8, 2019 Category : , 10


Installation : https://l-lin.github.io/angular-datatables/#/getting-started

Add a table to angular view


<table datatable [dtOptions]="dtOptions" style="width: 99.5% !important;" class="table table-responsive-sm table-bordered table-striped table-sm">
                                                <thead>
                                                    <tr>
                                                    <th>Client ID</th>
                                                    <th>Client Name</th>
                                                    <th>Client Phone</th>
                                                    <th>Join Date</th>
                                                    <th>Email</th>
                                                    <th>Is Active</th>
                                                    <th>Operation</th>
                                                    </tr>
                                                </thead>
                                                <tbody *ngIf="modelList && modelList?.length != 0">
                                                    <tr *ngFor="let m of modelList">
                                                    <td>{{ m.ClientID }}</td>
                                                    <td>{{ m.ClientName }}</td>
                                                    <td>{{ m.ClientPhone }}</td>
                                                    <td>{{ m.JoinDate | date : "MMM d, y" }}</td>
                                                    <td>{{ m.Email}}</td>
                                                    <td>
                                                            <div class="btn-group project-list-ad" *ngIf="m.IsActive">
                                                                    <button class="btn btn-white btn-xs">Active</button>
                                                            </div>

                                                            <div class="btn-group project-list-ad-rd" *ngIf="!m.IsActive">
                                                                    <button class="btn btn-white btn-xs">Unactive</button>
                                                            </div>
                                                    </td>
                                                    <td>
                                                        <button class="btn btn-pill btn-dark" type="button" (click)='editbuttonClick(m.ClientID)'>
                                                        <i class="fa fa-file-o fa-sm mt-1"></i>&nbsp;Edit
                                                        </button>
                                                    </td>
                                                    </tr>
                                                </tbody>
                                                <tbody *ngIf="!modelList || modelList?.length == 0">
                                                    <tr>
                                                    <td colspan="3" class="no-data-available">No data!</td>
                                                    </tr>
                                                <tbody>
                                                </table>

Type ScriptCode

dtOptions: DataTables.Settings = {};
public modelList: ClientList[]; // your model for store dataset
 

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10,
      serverSide: true,
      processing: true,
      ajax: (dataTablesParameters: anycallback=> {
        that._http
          .post<DataTablesResponse>(
            //'https://angular-datatables-demo-server.herokuapp.com/',
            this.env.apiUrl + 'api/setup/ClientList_SelectAll_Grid',
            dataTablesParameters, {}
          ).subscribe(resp => {
            //console.log(dataTablesParameters);
            that.modelList = resp.data;


            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
      },
      columns: [{ data: 'ClientID' }, { data: 'ClientName' }, { data: 'ClientPhone' }, { data: 'JoinDate' }, { data: 'Email' }, { data: 'IsActive' }, { defaultContent: ''orderable: false }]
    };

export class DataTablesResponse {
    data: any[];
    draw: number;
    recordsFiltered: number;
    recordsTotal: number;
    error :string;
  }
 

C# Server Side Code

 public class DataTablesRootObject
    {
        public int draw { getset; }
        public List<Columncolumns { getset; }
        public List<Orderorder { getset; }
        public int start { getset; }
        public int length { getset; }
        public Search search { getset; }
    }

    public class Search
    {
        public string value { getset; }
        public string product_segment { getset; }
        public string branchid { getset; }
        public string username { getset; }
        public string vendorno { getset; }

        public string fromdate { getset; }
        public string todate { getset; }

        public bool regex { getset; }
    }

    public class Column
    {
        public string data { getset; }
        public string name { getset; }
        public bool searchable { getset; }
        public bool orderable { getset; }
        public Search search { getset; }
    }

    public class Order
    {
        public int column { getset; }
        public string dir { getset; }
    }

public class DataTablesResponse
    {
        public object data { getset; }
        public int draw { getset; }
        public int recordsFiltered { getset; }
        public int recordsTotal { getset; }
        public string error { getset; }
    }

public DataTablesResponse ClientList_SelectAll_Grid([FromBodyDataTablesRootObject dataTablesRootObject)
        {
            //[FromBody] DataTablesRootObject dataTablesRootObject
            DataTablesResponse r = new DataTablesResponse();
            try
            {
                string searchText = "";
                if (dataTablesRootObject.search != null)
                {
                    searchText = dataTablesRootObject.search.value;
                }


                #region single sort code
                string sortInformAtion = "";

                if (dataTablesRootObject.order != null && dataTablesRootObject.order.Count > 0)
                {
                    if (dataTablesRootObject.columns != null && dataTablesRootObject.columns.Count > 0)
                    {
                        sortInformAtion = "ORDER BY " + dataTablesRootObject.columns[dataTablesRootObject.order[0].column].data + " " + dataTablesRootObject.order[0].dir;
                    }
                    //dataTablesRootObject.order[0].column
                }
                if (string.IsNullOrEmpty(sortInformAtion))
                {
                    sortInformAtion = "ORDER BY " + dataTablesRootObject.columns[0].data + " asc";
                }
                #endregion

                string error = "";
                List<DataModel.Setup.ClientListoListAll = serviceClientlist.GetsForGrid(dataTablesRootObject.startdataTablesRootObject.lengthsortInformAtionref errorsearchText);

                r.data = oListAll;

                r.draw = dataTablesRootObject.draw;
                r.error = error;
                if (oListAll != null && oListAll.Count > 0)
                {
                    r.recordsTotal = oListAll[0].RecordCount;
                    r.recordsFiltered = oListAll[0].RecordFilter;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.StackTrace);
            }
            return r;

        }


When table is not refresing after data added then add following code


Add trigger in html page

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" id="user-table"
                   class="table table-responsive-sm table-bordered table-striped table-sm">

Type Script code

implements AfterViewInit
 
declaration code

@ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
dtTrigger: Subject<TempRChallan= new Subject();
 



  ngAfterViewInit(): void {
    this.dtTrigger.next();
  }

  //ngOnDestroy(): void {
  //   Do not forget to unsubscribe the event
  //  this.dtTrigger.unsubscribe();
  //}

  rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api=> {
      // Destroy the table first
      dtInstance.destroy();
      // Call the dtTrigger to rerender again
      this.dtTrigger.next();
    });
  }

Call rerender method for table data reload.

C# .NET Cross-thread operation not valid: Control

Monday, November 4, 2019 Category : 1

Invoke(new Action(() =>
                            {
                                //progressBar1.Value = newValue;
                           


                            }));

Powered by Blogger.