Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe
I recently uploaded a ASP.net site to a host that uses plesk. For some reason file upload isn't working for the site on the host. I get an unknown error after I select a file to upload. But it works fine when I load the site on my local IIS server.
I'm not sure what may cause this error because the message doesn't specify the cause, so I'm not even sure where to begin looking.

Adbot
ADBOT LOVES YOU

beuges
Jul 4, 2005
fluffy bunny butterfly broomstick
Check file permissions in the upload folder on the server?

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe

beuges posted:

Check file permissions in the upload folder on the server?

oh my god that worked, can't believe it was that simple. Thanks!

Sab669
Sep 24, 2009

I'm working on an API for our web software and am having a little trouble building out the module that allows the user to upload a file.

In the actual Web project, it's done like so:

code:
foreach (string fileKey in Request.Files.Keys)
{
  HttpPostedFileBase uploadedFile = Request.Files[filekey];

  byte[] data;

  using (Stream inputStream = uploadedFile.InputStream)
  {
    MemoryStream memStream = inputStream as MemoryStream;
    
    data = memoryStream.ToArray();
  }

  _dbContext.Documents.Add(new Document()
  {
    DocumentId = ...
    DocumentSize = ...
    DocumentType = ...
    DocumentName = ...
    DocumentStream = data
  });
}
All of this code works perfectly fine. In the DB, that DocumentStream property is stored as a varbinary field.

To test uploading via the API, I uploaded a document from the actual Web software, and then copied the Data field from SQL Server to my clipboard to paste into Swagger while testing the API, but when I do this I get the error:

"The JSON value could not be converted to System.Byte[]. Path: $.data | LineNumber: 0 | BytePositionInLine: 6888"

Should I just make this field a string or something? I don't really understand why the Web project throws a byte[] into the field, but I can't throw the field into a byte[] from the API :thunk:

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Sab669 posted:

I'm working on an API for our web software and am having a little trouble building out the module that allows the user to upload a file.

In the actual Web project, it's done like so:

code:
foreach (string fileKey in Request.Files.Keys)
{
  HttpPostedFileBase uploadedFile = Request.Files[filekey];

  byte[] data;

  using (Stream inputStream = uploadedFile.InputStream)
  {
    MemoryStream memStream = inputStream as MemoryStream;
    
    data = memoryStream.ToArray();
  }

  _dbContext.Documents.Add(new Document()
  {
    DocumentId = ...
    DocumentSize = ...
    DocumentType = ...
    DocumentName = ...
    DocumentStream = data
  });
}
All of this code works perfectly fine. In the DB, that DocumentStream property is stored as a varbinary field.

To test uploading via the API, I uploaded a document from the actual Web software, and then copied the Data field from SQL Server to my clipboard to paste into Swagger while testing the API, but when I do this I get the error:

"The JSON value could not be converted to System.Byte[]. Path: $.data | LineNumber: 0 | BytePositionInLine: 6888"

Should I just make this field a string or something? I don't really understand why the Web project throws a byte[] into the field, but I can't throw the field into a byte[] from the API :thunk:

Your controller's code is probably most pertinent for figuring out what's going on here. Generally byte[] needs to be as serialized as something to go over the wire. It could a base64 string, it could be BSON...

No Pants
Dec 10, 2000

Whatever serializer is running there might be expecting a JSON array of numbers.

Sab669
Sep 24, 2009

Bruegels Fuckbooks posted:

Your controller's code is probably most pertinent for figuring out what's going on here. Generally byte[] needs to be as serialized as something to go over the wire. It could a base64 string, it could be BSON...

The full Web Controller (works) is as so:

code:
        [HttpPost]
        public async Task<ActionResult> UploadPartDocument(Guid partId, bool isFallback = false)
        {
            try
            {
                foreach (string filekey in Request.Files.Keys)
                {
                    HttpPostedFileBase uploadedFile = Request.Files[filekey];
                    byte[] data;

                    using (Stream inputStream = uploadedFile.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;

                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();

                            await inputStream.CopyToAsync(memoryStream);
                        }

                        data = memoryStream.ToArray();
                    }

                    _context.PartDocuments.Add(new PartDocument()
                    {
                        DocSize = uploadedFile.ContentLength,
                        DocStream = data,
                        DocType = uploadedFile.ContentType,
                        PartId = partId,
                        PartDocumentName = uploadedFile.FileName
                    });
                }

                await _context.SaveChangesAsync(); 

                if (isFallback)
                    return Content("<script type=\"text/javascript\">window.open('', '_self', '');window.close();</script>");
                else
                    return Json(new { Message = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Message = Resource.FileCouldNotBeUploaded + ex });
            }
        }
The full API controller (does not work)is:

code:
        [HttpPost]
        [Route("UploadPartDocument")]
        public ActionResult UploadPartDocument(PartsDocumentModel model)
        {
            if (!_apiDevFlagService.Enabled)
                return null; 

            _logger.Information("Create PartDocument request received"); 

            PartsDocumentDTO dto = new PartsDocumentDTO
            {
                ContentLength = model.ContentLength, //long
                Data = model.Data, //byte[]
                ContentType = model.ContentType, //string
                PartId = model.PartId, //guid
                FileName = model.FileName, //string
            };

            Guid result = _partsService.UploadPartDocument(dto); 
            return Json(result.ToString());
        }
And the actual service:

code:
        public Guid UploadPartDocument(PartsDocumentDTO dto)
        {
            Guid retVal = Guid.NewGuid(); 

            _db.PartDocuments.Add(new PartDocument
            {
                PartDocumentId = retVal,
                DocSize = dto.ContentLength,
                DocStream = dto.Data,
                DocType = dto.ContentType,
                PartId = dto.PartId,
                PartDocumentName = dto.FileName
            });

            _db.SaveChanges(); 

            return retVal;
        }
(Then once the API is working I'll refactor the Web controller to use the Service :))

SirViver
Oct 22, 2008
Is there a specific reason you try to send the file as a JSON payload? Usually files over HTTP are sent as multipart/form-data request, which is what I believe Request.Files resolves under the hood in the Web Controller.

With Web API you need to do this resolving a bit more manually, like described here:
https://web.archive.org/web/2012051...e#multipartmime

E: actually you can do this the same way via HttpContext.Current.Request.Files in WebAPI.

That way the request to Web Controller and Web API would look the same, just to a different URL. If you do need to go the JSON route then you'll need to encode the byte content of the document as a base64 string or similar. Trying to send actual "byte"/number arrays would be incredibly inefficient.

SirViver fucked around with this message at 15:17 on May 19, 2020

Sab669
Sep 24, 2009

SirViver posted:

Is there a specific reason you try to send the file as a JSON payload? Usually files over HTTP are sent as multipart/form-data request, which is what I believe Request.Files resolves under the hood in the Web Controller.

To be honest I don't really know what I'm doing :v: I don't have much experience with writing APIs or handling files.

I didn't write the web controller either, and the senior architect was fired just as all this covid poo poo went down so I'm kind of on my own here :) I figured I'd just try to keep this as close to how the rest of the API wass being written for all our "business entities" within the software where we just pass in some JSON values and convert it to an object and write it to the DB.

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe
An ajax get is giving me an 404 error on the server but the function works fine locally.
Locally the variable 'data' returns true and everything works fine, but on the server 'data' returns a generated html code with 404 errors.
I googled and found a lot of people with similar issues but the solutions were really specific.

This is the function
code:
function ClearCart() {
    $.ajax({
        type: "get",
        url: "Tools/ShoppingCart/Clear.aspx",
        datatype: "json",
        success: function (data) {
			console.log(data)
            if (data == "true") {
                Shopping_Cart();
            }
            else {
                alert("Failed to load! Error Code:048", "error");
            }
        },
        error: function (msg) {
            alert("Failed to load! Error Code:049", "error");
        }
    });
}
This is what the server spits out:
code:
ShoppingCard.js?spm=12:355 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta charset="utf-8" /><title>
	Sorry&#65292;The page does not exist&#65281;
</title><link href="css/style.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="js/banner_01.js"></script>
    <script type="text/javascript" src="js/myJs.js"></script>
</head>
<body> 
    <div class="inside_about wapper">
        <div>
            <table width="100%">
                <tr>
                    <td style="width: 600px;">
                        <img src="images/error404.jpg" />
                    </td>
                    <td>
                        <table>
                            <tr>
                                <td style="font-size: 28px; border-bottom: 1px solid #aaa; height: 50px;">
                                    Page not accessible
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <p>
                                        Probable Cause&#65306;</p>
                                    <ul class="reason-list">
                                        <li>Incorrect URL<span><i class="gt">&gt;</i>Ensure address is correct</span></li>
                                        <li>URL has expired<span><i class="gt">&gt;</i>Page may have been deleted</span></li>
                                    </ul>
                                </td>
                            </tr>
                            <tr>
                                <td style="font-size: 14px;">
                                    <a href="default.aspx" style="color: #7F0019;"><< Back to Home</a>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </div>
    </div> 
</body>
</html>

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

SirViver posted:

Is there a specific reason you try to send the file as a JSON payload? Usually files over HTTP are sent as multipart/form-data request, which is what I believe Request.Files resolves under the hood in the Web Controller.

This. His code is fine, or close enough. The problem is that he's testing it using Swagger (I assume he means Swagger UI), which doesn't have a file upload button, just a text field that becomes the request body.

Test the API with something like Postman and you'll be able to attach actual files to the request.

Sab669
Sep 24, 2009

NihilCredo posted:

This. His code is fine, or close enough. The problem is that he's testing it using Swagger (I assume he means Swagger UI), which doesn't have a file upload button, just a text field that becomes the request body.

Test the API with something like Postman and you'll be able to attach actual files to the request.

Oh, this :downs: I do have Postman but I've never used it. The aforementioned sr architect we lost had me download it but never had time to tell me what it was for :)

Jen heir rick
Aug 4, 2004
when a woman says something's not funny, you better not laugh your ass off

NihilCredo posted:

This. His code is fine, or close enough. The problem is that he's testing it using Swagger (I assume he means Swagger UI), which doesn't have a file upload button, just a text field that becomes the request body.

Test the API with something like Postman and you'll be able to attach actual files to the request.

You can get swagger ui to display a file button with the right annotations, but it requires a bit of futzing about depending on what version of swashbuckle you’re using. Assuming he’s using swashbuckle.

SirViver
Oct 22, 2008

Revalis Enai posted:

An ajax get is giving me an 404 error on the server but the function works fine locally.

Erm, have you tried looking in the browser's dev console network log to see what the actual full request URL of that ajax call is? Maybe it tries to navigate from the website root (or not from root), resulting in the wrong URL being called? At least that's usually a problem I encounter when running in Visual Studio's built in webserver vs. applications actually running on IIS.

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe

SirViver posted:

Erm, have you tried looking in the browser's dev console network log to see what the actual full request URL of that ajax call is? Maybe it tries to navigate from the website root (or not from root), resulting in the wrong URL being called? At least that's usually a problem I encounter when running in Visual Studio's built in webserver vs. applications actually running on IIS.

The full request url of the server is
code:
https://website.com/Tools/ShoppingCart/Clear.aspx
The full request url of my local server is
code:
http://192.168.1.181:8099/Tools/ShoppingCart/Clear.aspx
My local server shows a status code of 200 ok while the live server is showing status code 302 found

mystes
May 31, 2006

Revalis Enai posted:

The full request url of the server is
code:
https://website.com/Tools/ShoppingCart/Clear.aspx
The full request url of my local server is
code:
http://192.168.1.181:8099/Tools/ShoppingCart/Clear.aspx
My local server shows a status code of 200 ok while the live server is showing status code 302 found
If you're sure everything about the server is the same and it must be a problem with your request, you might want to look at the actual request headers with something like wireshark to make sure that everything is actually the same.

mystes fucked around with this message at 21:57 on May 19, 2020

Jen heir rick
Aug 4, 2004
when a woman says something's not funny, you better not laugh your ass off

Revalis Enai posted:


My local server shows a status code of 200 ok while the live server is showing status code 302 found

302 is a redirect, look at the response header and see what it’s trying to redirect to.

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe

Jen heir rick posted:

302 is a redirect, look at the response header and see what it’s trying to redirect to.

I looked at the header for Clear.aspx from both sites and only the live server shows a location
code:
Location: /errorpage.aspx?aspxerrorpath=/Tools/ShoppingCart/Clear.aspx
I'm not sure what it means, but I'm guessing that something happened while executing Clear.aspx and it's generating an errorpage?

Jen heir rick
Aug 4, 2004
when a woman says something's not funny, you better not laugh your ass off

Revalis Enai posted:

I looked at the header for Clear.aspx from both sites and only the live server shows a location
code:
Location: /errorpage.aspx?aspxerrorpath=/Tools/ShoppingCart/Clear.aspx
I'm not sure what it means, but I'm guessing that something happened while executing Clear.aspx and it's generating an errorpage?

It’s trying to redirect to an error page, but Ajax calls won’t follow redirects. You should try making the same call using Postman.

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe
I tried to access clear.aspx from my local server and I get a blank page with the word 'true' in the page, which is what I expected to see.
When I tried to access clear.aspx from the live server, it directs me to the custom 404 error page. Right now what I don't know is why it's doing so. I
Other aspx files on the live server seem to be loading up with no issue.

The header from the live server has some additional items. I also noticed the content length from the local server is longer than the live server.

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe
I was finally able to fix the issue!

I found a way to temporary stop the redirect and to have the site show me what error was actually being thrown out.
This is what it came up:

code:
[MethodAccessException: Attempt by security transparent method 'Basic.Tools.Utils.getLocalMac()' to access security critical method 'System.Management.ManagementObjectSearcher..ctor(System.String)' failed.
I googled the error and one of the solution was to add trust level into the web.config file. So I added
code:
<trust level="Medium" /> 
and now clear.aspx runs with no issue.

I'm still new to ASP.net but having to debug someone else's code is forcing me to cram as much into my brain as quickly as possible.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
Azure question

Does anyone else here work with Azure Functions? I've noticed that they recently redid the whole layout, and in general it's much better. But they seem to have removed the option to see Console output from the invocations, is this gone for real or am I missing a setting somewhere to turn it back on? All I see is "Logs" at the bottom, which only updates with an occasional line of output, not all of them.

Boz0r
Sep 7, 2006
The Rocketship in action.
We've got some ASP.NET Framework projects that use dependency injection. Some classes take 8-10 different injected classes, and I think it looks cluttered. Is there a better way?

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

Boz0r posted:

We've got some ASP.NET Framework projects that use dependency injection. Some classes take 8-10 different injected classes, and I think it looks cluttered. Is there a better way?

If it's like most projects, 6-7 of those classes are basic stuff that virtually everything depends on, like loggers and databases. Wrap those in a "commons" POCO and inject that.

EssOEss
Oct 23, 2006
128-bit approved
Just accept it and move on. Yes, if your class has 15 dependencies, you need to list 15 dependencies. By hiding that you'll make more trouble for yourself and your readers later on. Be explicit.

Some things in life just are.

raminasi
Jan 25, 2005

a last drink with no ice
If any of those dependencies can use null implementations and aren’t relevant in unit tests, you can use property injection to tidy up your constructors. I’ve seen this work well with logging specifically but there might easily be other cases where it works well.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Boz0r posted:

We've got some ASP.NET Framework projects that use dependency injection. Some classes take 8-10 different injected classes, and I think it looks cluttered. Is there a better way?

Your classes are too big and doing too much.

Potassium Problems
Sep 28, 2001

New Yorp New Yorp posted:

Your classes are too big and doing too much.

it's this. also, the decorator pattern might help with concerns like logging.

redleader
Aug 18, 2005

Engage according to operational parameters
26-parameter constructor crew checking in

B-Nasty
May 25, 2005

New Yorp New Yorp posted:

Your classes are too big and doing too much.

Yep, it's a really stinky code smell that you need to start breaking apart or clustering those dependencies.

Plenty of DI tips on this blog: https://blog.ploeh.dk/2018/08/27/on-constructor-over-injection/

insta
Jan 28, 2009

NihilCredo posted:

If it's like most projects, 6-7 of those classes are basic stuff that virtually everything depends on, like loggers and databases. Wrap those in a "commons" POCO and inject that.

wtf no

SimonChris
Apr 24, 2008

The Baron's daughter is missing, and you are the man to find her. No problem. With your inexhaustible arsenal of hard-boiled similes, there is nothing you can't handle.
Grimey Drawer

StrixNebulosa posted:

I think my favorite thing about Autonauts so far is how stupid these robots are. They do exactly what you tell them to do and nothing more.

For example! One robot I set up to find robots in a specific area and recharge them. I figured it could handle three areas. NOT SO.

It would do one area, then move to the second, then to the third. The third only had one robot in it, so it would wait like the 5 minutes for them to wind down, recharge them, and then it would go back to the first two areas.... completely neglecting that there were like 10 robots waiting for recharges, because it was told to do the areas in sequence.

The game is like. "these are dumb robots. instead of giving them complex instructions, make more robots."

So now I have a robot who collects sticks into a bin, one who takes sticks to the axe-making bench, and one who gets rocks, and so on. Because I cannot trust these little idiots to do more than one or two tasks at a time without getting confused. (I love them dearly and am glad I have like 20 of them now.)

I just found this in the Steam thread.

Nth Doctor
Sep 7, 2010

Darkrai used Dream Eater!
It's super effective!


SimonChris posted:

I just found this in the Steam thread.

Strix is becoming enlightened.

EssOEss
Oct 23, 2006
128-bit approved

New Yorp New Yorp posted:

Your classes are too big and doing too much.

Maybe. Sometimes your class just implements 1 simple concept and needs to call 10 different things once or twice when doing so.

If you can post code, Boz0r, we might be able to offer specific advice on how to do better. What is "better" here can be very situational and it's easy to get carried away by doing low-cost-effectiveness changes just for theoretical benefit.

Boz0r
Sep 7, 2006
The Rocketship in action.
Are there any tools for keeping track of Nuget packages and their dependencies? Our client has developed a sudden interest in packaging our projects, and now I've got missing dependencies from a Nuget package's dependency, or something.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

Boz0r posted:

Are there any tools for keeping track of Nuget packages and their dependencies? Our client has developed a sudden interest in packaging our projects, and now I've got missing dependencies from a Nuget package's dependency, or something.

You can either enable the creation of lock files or start using Paket.

Boz0r
Sep 7, 2006
The Rocketship in action.

EssOEss posted:

Maybe. Sometimes your class just implements 1 simple concept and needs to call 10 different things once or twice when doing so.

If you can post code, Boz0r, we might be able to offer specific advice on how to do better. What is "better" here can be very situational and it's easy to get carried away by doing low-cost-effectiveness changes just for theoretical benefit.

Someone had the brilliant idea of wrapping our DbContext-equivalent for CRM in a SAL that exposes set queries. Each entity has their own Service Manager, and the DI is injecting 8 different Service Managers because the BLL needs 8 different entities.

Mr Shiny Pants
Nov 12, 2012

Boz0r posted:

Someone had the brilliant idea of wrapping our DbContext-equivalent for CRM in a SAL that exposes set queries. Each entity has their own Service Manager, and the DI is injecting 8 different Service Managers because the BLL needs 8 different entities.

That totally does not sound convoluted in any way. This seems the be big issue with these "patterns", people think they have to do it "everywhere" otherwise they suck as a coder.

redleader
Aug 18, 2005

Engage according to operational parameters

Boz0r posted:

Someone had the brilliant idea of wrapping our DbContext-equivalent for CRM in a SAL that exposes set queries. Each entity has their own Service Manager, and the DI is injecting 8 different Service Managers because the BLL needs 8 different entities.

oh yeah, we do a similar thing - hence the class with 26+ parameters in its constructor

Adbot
ADBOT LOVES YOU

Boz0r
Sep 7, 2006
The Rocketship in action.
How much do you use nuget packages? We've got an old repo in TFS that's using a proxy nuget package to communicate with our new web services in git. We've got a solution for each different web service, and a couple of shared projects. Someone has started making nuget packages of the shared projects to avoid shared dependencies in projects, and I don't really see the point, and I don't know if it'll screw with some of our tools.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply