System.NullReferenceException: Object reference not set to an instance of an object. at ESRI.ArcGIS.Azure.Publish_Web.Controllers.

951
1
09-21-2020 09:52 PM
Eidul_AmeenSahul_Hamid
New Contributor

I am going through the following tutorial to add shape file to my map.

Add shapefile | ArcGIS API for JavaScript 3.33 

My code is as follows:

arcgisMapShape: function () {
           
  
            var map;
            var layers = [];

            require([
              "esri/config",
              "esri/InfoTemplate",
              "esri/map",
              "esri/request",
              "esri/geometry/scaleUtils",
              "esri/layers/FeatureLayer",
              "esri/renderers/SimpleRenderer",
              "esri/symbols/PictureMarkerSymbol",
              "esri/symbols/SimpleFillSymbol",
              "esri/symbols/SimpleLineSymbol",
              "dojo/dom",
              "dojo/json",
              "dojo/on",
              "dojo/parser",
              "dojo/sniff",
              "dojo/_base/array",
              "esri/Color",
              "dojo/_base/lang",
              "dijit/layout/BorderContainer",
              "dijit/layout/ContentPane",
              "dojo/domReady!"
            ],
              function (
              esriConfigInfoTemplateMaprequestscaleUtilsFeatureLayer,
              SimpleRendererPictureMarkerSymbolSimpleFillSymbolSimpleLineSymbol,
              domJSONonparsersniffarrayUtilsColorlang
            ) {
                loadingState = "Loading";
                parser.parse();

                var portalUrl = "https://www.arcgis.com";

                esriConfig.defaults.io.proxyUrl = "/proxy/";

              

                // $('table').on('click', '.btn-remove-aktiviti', function (e) {
                // $("#btn-remove-aktiviti").click(function(e) {
                // on(dom.byId("btn-remove-aktiviti"), "click", function (e) {
                //     $(this).parents('tr').remove()

                //     resetAktiviti();
                // });

                // $('wizard_with_validation').on('change', '#inFile', function (event) {
                on(dom.byId("inFile"), "change"function (event) {
                  var fileName = event.target.value.toLowerCase();

                  if (sniff("ie")) { //filename is full path in IE so extract the file name
                    var arr = fileName.split("\\");
                    fileName = arr[arr.length - 1];
                  }
                  if (fileName.indexOf(".zip") !== -1) {//is file a zip - if not notify user
                    generateFeatureCollection(fileName);
                  }
                  else {
                    dom.byId('upload-status').innerHTML = '<p style="color:red">Add shapefile as .zip file</p>';
                  }
                });

                // var mapid="d5e02a0c1f2b4ec399823fdd3c2fdebd"
                // map = esri.arcgis.utils.createMap(mapid, "mapCanvas", {
                //   mapOptions: {
                //     basemap: "hybrid",
                //     center: [103.791096, 1.547069],
                //     slider: true,
                //     nav:false
                //   }
                // });
                map = new Map("mapCanvas", {
                  basemap: "topo",
                  center: [101.9758 , 4.2105],
                  zoom: 6,
                  slider: true,
                  logo: true,
                  showAttribution: false
                });

                function generateFeatureCollection (fileName) {
                  var name = fileName.split(".");
                  //Chrome and IE add c:\fakepath to the value - we need to remove it
                  //See this link for more info: http://davidwalsh.name/fakepath
                  name = name[0].replace("c:\\fakepath\\""");

                  dom.byId('upload-status').innerHTML = '<b>Loading </b>' + name;

                  //Define the input params for generate see the rest doc for details
                  //http://www.arcgis.com/apidocs/rest/index.html?generate.html
                  var params = {
                    'name': name,
                    'targetSR': map.spatialReference,
                    'maxRecordCount': 1000,
                    'enforceInputFileSizeLimit': true,
                    'enforceOutputJsonSizeLimit': true
                  };

                  //generalize features for display Here we generalize at 1:40,000 which is approx 10 meters
                  //This should work well when using web mercator.
                  var extent = scaleUtils.getExtentForScale(map40000);
                  var resolution = extent.getWidth() / map.width;
                  params.generalize = true;
                  params.maxAllowableOffset = resolution;
                  params.reducePrecision = true;
                  params.numberOfDigitsAfterDecimal = 0;

                  var myContent = {
                    'filetype': 'shapefile',
                    'publishParameters': JSON.stringify(params),
                    'f': 'json',
                    'callback.html': 'textarea'
                  };

                  //use the rest generate operation to generate a feature collection from the zipped shapefile
                  request({
                    url: portalUrl + '/sharing/rest/content/features/generate',
                    content: myContent,
                    form: dom.byId('wizard_with_validation'),
                    handleAs: 'json',
                    load: lang.hitch(thisfunction (response) {
                      if (response.error) {
                        errorHandler(response.error);
                        return;
                      }
                      var layerName = response.featureCollection.layers[0].layerDefinition.name;
                      dom.byId('upload-status').innerHTML = '<b>Loaded: </b>' + layerName;
                      addShapefileToMap(response.featureCollection);
                    }),
                    error: lang.hitch(thiserrorHandler)
                  });
                }

                function errorHandler (error) {
                  dom.byId('upload-status').innerHTML =
                  "<p style='color:red'>" + error.message + "</p>";
                }

                function addShapefileToMap (featureCollection) {
                  //add the shapefile to the map and zoom to the feature collection extent
                  //If you want to persist the feature collection when you reload browser you could store the collection in
                  //local storage by serializing the layer using featureLayer.toJson()  see the 'Feature Collection in Local Storage' sample
                  //for an example of how to work with local storage.
                  var fullExtent;
                  // var layers = [];
                  // console.log(layers);
                  if (layers.length != 0) {
                    map.removeLayer(layers[0]);
                    layers = [];
                  }
                  arrayUtils.forEach(featureCollection.layersfunction (layer) {
                    var infoTemplate = new InfoTemplate("Details""${*}");
                    var featureLayer = new FeatureLayer(layer, {
                      infoTemplate: infoTemplate
                    });
                    
                    //associate the feature with the popup on click to enable highlight and zoom to
                    featureLayer.on('click'function (event) {
                      map.infoWindow.setFeatures([event.graphic]);
                      console.log([event.graphic]);
                      var attributes = event.graphic.attributes;
                      // var nama_proje = event.graphic.attributes.NAMA_PROJE;
                      var latitude = event.graphic.attributes.LATITUDE;
                      var longitude = event.graphic.attributes.LONGITUDE;
                      var negeri = event.graphic.attributes.NEGERI;
                      var daerah = event.graphic.attributes.DAERAH;
                    //   var bandar = event.graphic.attributes.BANDAR;
                      var mukim = event.graphic.attributes.MUKIM;
                    //   var parlimen = event.graphic.attributes.PARLIMENT;
                    //   var dun = event.graphic.attributes.DUN;

                      console.log(longitude);
                      console.log(latitude);
                      console.log(negeri);
                      // dom.byId('nama_projek').value = nama_proje;
                      dom.byId('latitud').value = latitude;
                      dom.byId('longitud').value = longitude;
                      dom.byId('negeri').value = negeri;
                      dom.byId('daerah').value = daerah;
                    //   dom.byId('bandar').value = bandar;
                      dom.byId('mukim').value = mukim;
                    //   dom.byId('parlimen').value = parlimen;
                    //   dom.byId('dun').value = dun;
                    });
                    //change default symbol if desired. Comment this out and the layer will draw with the default symbology
                    changeRenderer(featureLayer);
                    fullExtent = fullExtent ?
                      fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
                    layers.push(featureLayer);
                  });
                  map.addLayers(layers);
                  map.setExtent(fullExtent.expand(1.25), true);

                  dom.byId('upload-status').innerHTML = "";
                }

                function changeRenderer (layer) {
                  //change the default symbol for the feature collection for polygons and points
                  var symbol = null;
                  switch (layer.geometryType) {
                    case 'esriGeometryPoint':
                      symbol = new PictureMarkerSymbol({
                        'angle': 0,
                        'xoffset': 0,
                        'yoffset': 0,
                        'type': 'esriPMS',
                        'url': 'https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png',
                        'contentType': 'image/png',
                        'width': 20,
                        'height': 20
                      });
                      break;
                    case 'esriGeometryPolygon':
                      symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                        new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                          new Color([112112112]), 1), new Color([1361361360.25]));
                      break;
                  }
                  if (symbol) {
                    layer.setRenderer(new SimpleRenderer(symbol));
                  }
                }
              });

          },

But when I add the code and run the program, i am getting the following error.
System.NullReferenceException: Object reference not set to an instance of an object. at ESRI.ArcGIS.Azure.Publish_Web.Controllers.GenerateFeaturesController.GetGenerateFeaturesOperationModelFromRequest() in C:\agents\warlockbld-win0\3\src\MTPublisher\Publish_Web\Controllers\GenerateFeaturesController.cs:line 388 at ESRI.ArcGIS.Azure.Publish_Web.Controllers.GenerateFeaturesController.Index(String id, FormCollection collection) in C:\agents\warlockbld-win0\3\src\MTPublisher\Publish_Web\Controllers\GenerateFeaturesController.cs:line 59 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.b__41() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.b__20() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__22(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) at System.Web.Mvc.Controller.<>c__DisplayClass1d.b__18(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.b__3(IAsyncResult ar) at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.b__3(IAsyncResult ar) at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__3(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.b__3(IAsyncResult ar) at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.<>c__DisplayClass285_0.b__0() at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Tags (2)
0 Kudos
1 Reply
Eidul_AmeenSahul_Hamid
New Contributor

Solve the problem..

just need to change the following code

<input type="file" name="inFile" id="inFile" class="dropify">

to

<input type="file" name="file" id="inFile" class="dropify">
0 Kudos