Help Rendering ASP.NET MVC View from a Console App

Someone asked on Stack Overflow:

I have created an ASP.NET MVC View. On my MVC WebApp, it works great.

I would like to be able to (from a console app) render the View out as an HTML Email. I’m wondering what the best way to do this is going to be, the part I’m struggling with is Rendering the View.

Is there any way to do this from a console application?

The webapp simply calls a web-service and formats the data nicely so the console application will have access to the same web-service; however, the ActionResult on the controller is protected by [Authorize] attributes, so not just anyone can get at it.

I posted the following answer, which was chosen as the accepted answer:

I ended up using HttpWebRequest and the info provided here: http://odetocode.com/articles/162.aspx

From the article:

    // first, request the login form to get the viewstate value
    HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;         
    StreamReader responseReader = new StreamReader(
         webRequest.GetResponse().GetResponseStream()
      );
    string responseData = responseReader.ReadToEnd();         
    responseReader.Close();

    // extract the viewstate value and build out POST data
    string viewState = ExtractViewState(responseData);       
    string postData = 
         String.Format(
            "__VIEWSTATE={0}&UsernameTextBox={1}&PasswordTextBox={2}&LoginButton=Login",
            viewState, USERNAME, PASSWORD
         );

    // have a cookie container ready to receive the forms auth cookie
    CookieContainer cookies = new CookieContainer();

    // now post to the login form
    webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.CookieContainer = cookies;        

    // write the form values into the request message
    StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
    requestWriter.Write(postData);
    requestWriter.Close();

    // we don't need the contents of the response, just the cookie it issues
    webRequest.GetResponse().Close();

    // now we can send out cookie along with a request for the protected page
    webRequest = WebRequest.Create(SECRET_PAGE_URL) as HttpWebRequest;
    webRequest.CookieContainer = cookies;
    responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

    // and read the response
    responseData = responseReader.ReadToEnd();
    responseReader.Close();

    Response.Write(responseData); 

Originally posted on Stack Overflow — 0 upvotes (accepted answer). Licensed under CC BY-SA.

Save File sharing over Mobile Networks

Someone asked on Game Development:

I’m looking to have people share game content, save files, or characters on a mobile game platform. That means they need to be able to upload and download from their phone, other iOS device, or computer.

What’s the best way to do this?

Does Apple have a history of allowing games to download ‘content’ (incl. graphics) that hasn’t been approved?

Are there any apps that do this, that I can try out?

Thanks,


[EDIT]

The files I want to share will be simple *.plist files, probably in binary format.

I posted the following answer, which was chosen as the accepted answer and received 1 upvote:

You’ll want to use something like Amazon S3 or Azure Blob storage. Both of these services will charge you for data transfer both IN and OUT; as well as the average storage amount you are using on their servers.

They both offer a simple API to read and write data to and from, you can write iOS, Android, BlackBerry, Windows, Mac, Linux, etc versions of your application, which would all consume the same web service API. This gives you the ability to have users interact with data on any platform, and have those changes immediatly available on any other platform.

Optionally, you could write a simple web-service which handles your data conversion between platforms, you could use something like Amazon EC2 to host a service like this. Depending on the complexity of the data you are storing this might be over-kill.

Notable comments

Nate (0 upvotes): I believe they expose a Dictionary type interface (key,value pairs) and as such searching may be difficult if you don’t have the key. That said, I know that Azure offers SQL Azure which functions exactly like a SQL database (minus a few enterprise features) which would allow you to search. If your data is small, using one of these SQL Azure instances should not greatly increase the cost ($9.99/month for 1GB database iirc).

Nate (0 upvotes): It really depends on the complexity of the files, and where the OP intends to implement the code — it would not be unreasonable to have a small parser inside each version of the application, so it can both serialize and deserialize the data to the web service persistence tier (S3 or whatever it ends up being). Updated the post to include my thoughts on it.


Originally posted on Game Development — 1 upvotes (accepted answer). Licensed under CC BY-SA.

Does Streaming a WCF Soap Help the Client Send Using Less Memory?

Someone asked on Stack Overflow:

I have a windows mobile application that sends data via WCF to a server.

The data it sends sometimes exceeds the limit on the windows mobile device. I am wondering if streaming would help not need to hold all the data I must send in memory at once.

Here is a simple example:

[DataContract]
public class MainContract
{
    [DataMember]
    public Guid  ID { get; set; }

    [DataMember]
    public List<SubContract> SubContract { get; set; }
}

[DataContract]
public class SubContract
{
    [DataMember]
    public Guid ID { get; set; }

    [DataMember]
    public string ImageCaption { get; set; }

    [DataMember]
    public Byte[] ImageAsBytes { get; set; }
}

Say I have only 1 MainContract object. But it has a lot of SubContract objects in it. (My real scenario is more compelex).

Holding all of MainContract in memory is too much for the client side to do.

Will streaming allow me to send send the data over the wire in pieces? Or do I still have to buffer it all on the client side and the streaming just helps with the receiving of large data?

I posted the following answer, which was chosen as the accepted answer and received 1 upvote:

As far as I know, if your method accepts a MainContract you will need to have that completely in memory on the client side in order to stream the serialized result to the WCF host.

If loading up a full MainContract will take too much memory on the client side, I would adjust the service to allow for something like this:

public Guid CreateMainContract(MainContract obj); // return unique id
public Guid CreateSubContract(Guid mainContractToAddTo, SubContract obj);

and then modify the calling code to pseduo-stream the data to the WCF host, by means of calling the above operations in a loop. (Obviously, you’ll need to change it up for update/delete situations, etc).


Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.

What is the best algorithm to visually separate overlapping vehicles in close proximity on a map?

Someone asked on Stack Overflow:

I am looking for an algorithm that will allow me to visually separate any two to four vehicles within a large list of vehicles that are close enough together on a map such that they obscure one another. I need to filter out instances where there are more than four vehicles as the vehicles will congregate in certain areas in large quantities and it is unimportant to separate them in those cases. The algorithm should also mark vehicles that have already been processed.

In my problem space, it is more important to know that the vehicles are present and to be able to see information about them, than to have absolutely accurate information as to where they are.

The idea is to add approximately 10 yards (given the map scale that is being used) so individual vehicles can be seen instead of being obscured by other vehicles in close proximity.

I have thought of several ways to do this, but given the quality of the answers here and the fact that somebody might have already done this, I thought I would post the question.

I am adding an image of what is currently shown in order to help clarify as one of the comments suggested (OK, it is not a diagram but this is what is actually shown to the user).

Several of the answers require changing the visual queues used to indicate how many vehicles (golf cars) are in a given location. I don’t want to change what the users are expecting visually and have to explain to the users what the meaning is. The answer using a square is closest to what I was looking for but that is just the visual part. I am also looking for the algorithm for how to best traverse the list finding groups of 2 to 4 golf cars that are within n (lets say 5) yards of each other while ignoring larger groupings (cart barn, snack shack, etc). The numbers on the icons correspond to the cart numbers.

This application also allows the user to zoom the map in/out so the further zoomed out the map the more separation is needed between the cars so that they do not visually overlap.

Note in the picture that cars 78 and 62 are obscuring the cars that are behind them.

alt text

I posted the following answer, which was chosen as the accepted answer:

A square seems like a good candidate since you are not worried about instances with more than four vehicles.

I would take the average location of all vehicles in “overlapping” proximity, and set this as the “center” of the square, with length and width sufficently large that putting a vehicle on each corner will not result in any overlap.

Then I would start with vehicle 0 at the top left and work my way around the corners of the square counter clockwise, adding the next vehicle to the next corner.

Simple, and effective, you lose some accuracy, assuming thats OK (from your post it seems it is?) this is what I woul do.


Originally posted on Stack Overflow — 0 upvotes (accepted answer). Licensed under CC BY-SA.

Tools for planning a SQL Database size requirement

Someone asked on Server Fault:

I’m about ready to start setting up a SQL data warehouse for some SQL Server Analysis Services. The data that I am going to slice and dice lives in an off site database that I don’t control, so my idea is to set up regular jobs that go out and pick up new entries and insert them in to my own version of the table.

I am wondering if there are any good tools out there to help plan database space requirements. After only 5 months the table that I am interested in has already got almost 4.5 Million records and by this time next year I estimate that we could be generating 3-4 million records a month.

I guess what I’m looking for is something that I can feed the table definition in to, and then tell me how much disk space a billion rows would take.

Thanks.

Edit


Well, using Excel I came up with a theoretical 1098 bytes per record using the worst case scenario that a varchar(1000) was used in every single record to the max.

At 4 million records per month that’s 48 million records a year and a worst case need of 50 gigs of disk space per year. Dropping that to a varchar(255) gives me not quite 16 gigs per year, and varchar(50) gives me ~6.5 gigs per year.

Anybody out there a better DBA than I am and let me know if I’m way off base or not?

Edit #2


As requested here is the table definition:

Type             Size
int              4
int              4
int              4
datetime         8
Decimal(19,5)    9
int              4
int              4
varchar(1000)    1000
int              4
int              4
smalldatetime    4
int              4
int              4
int              4
int              4
decimal(9,2)     5
smallint         2
datetime         8
decimal(18,2)    9
bit              1
int              4
int              4

Grand total of 1098 bytes if all fields are used to the max.

I posted the following answer, which was chosen as the accepted answer and received 1 upvote:

I don’t know of any tools that will do this; however, while it is a bit of a pain, you can calculate this your self based on the row’s column types. You could probably write a powershell to help you if you output the create table scripts and fed them into a script.

Maybe a script that searches for all int and adds to a counter, and the same for each data type, then you can do some quick multiplication to figure out an approx. table size. It will probably be somewhat tricky to pickup the sizes of all the varchar(50) and char(10) data types, but again, a bit of powershell magic could probably help.

Update


I too come to the same conclusion you have, in the worst case you are at 1098 bytes per record. You know your data, but based on your edits it seems like there is a good chance that your data will be less than varchar(1000) for many records. This will give you space savings on every record when this is the case, so in the best case you are at 98 bytes per record. If I were you, I would use this information to check the data you already have, and come up with a base-line for the average length of this varchar(1000) field and use that average to calculate a nice median.

Notable comments

Nate (0 upvotes): Sure, it also helps that you looked up the sizes for your column types, thats the hard part of this, not the addition ;)


Originally posted on Server Fault — 1 upvotes (accepted answer). Licensed under CC BY-SA.

How to reduce App (.apk) Size

Someone asked on Stack Overflow:

Help!

When I install my app on the phone to test, it is showing up to be a HUGE size, 11.35 MB. It is a very simple app that lets user browse through fun-facts. The only reason I can think of is that there are 14 JPEG files in the drawables which serve as background images of the fun-facts. The average size of these is about 500 KB.

I’d like to trim the size of my app, so as not to use up the precious resources on the user’s device. Other than just getting rid of the pictures, are there ways to optimize the size of apk file?

EDIT: The pictures are photos taken by me using the Android phone itself.

I posted the following answer, which was chosen as the accepted answer and received 24 upvotes:

I would recommend that you compress the .jpg files as much as possible, this should greatly reduce the size of your .apk file. A tool such as Paint.NET which is free should help you do this. It has great resizing options.

Notable comments

Nate (0 upvotes): Good point, but depending on the level of compression in the images, there could be room for additional compression in addition to reducing the size.


Originally posted on Stack Overflow — 24 upvotes (accepted answer). Licensed under CC BY-SA.

VB6 ActiveX Controls in a C#/ASP.NET Based Website

Someone asked on Stack Overflow:

We have a website that is based on C# and ASP.NET, I have a barcode scanner with a .dll file to control it that I can get to work in VB6. Before I dig deeper in exactly how to do this I wanted a quick answer on if it is even possible to do what I want first.

Can I write an activex control in VB6 that will allow me to control the barcode scanner and implement that activex control in our .NET based website?

Just to be clear, not asking HOW to do it, just asking if it can be done. I haven’t done any ActiveX programming before and haven’t touched VB6 in a long time.

Thanks!

I posted the following answer, which was chosen as the accepted answer:

I believe it should be possible; but you will probably need to implement it with JavaScript and ActiveX objects. This will require that the user’s browser is setup to allow your web site to interact with ActiveX objects. A simple example of this, is using a link to start a program (like remote desktop client):

<script type="text/javascript">
    function runMstsc() {
        var command="mstsc.exe /v:127.0.0.1 /w:1024 /h:768";
        var scriptHost = new ActiveXObject("WScript.Shell");
        scriptHost.run(File);
    }
</script>

Assuming that your application is a valid ActiveX control, you should be able to minipulate it in a similar fashion to WScript.Shell.


Originally posted on Stack Overflow — 0 upvotes (accepted answer). Licensed under CC BY-SA.

How to handle a Sprite Class?

Someone asked on Game Development:

Currently I am learning XNA and while playing around with some tutorials knowing what I am aiming for a game it made me think that the Sprite Class will be something very important and re-used a lot of times, not sure if I am mistaken or not with this thinking.

Bellow you can see the Sprite code I am using at the momment and I was wondering:

  • How a Sprite Class should be or what functions in general it should have or am I mistaken that the Sprite Class will not be used by every sprite in my game ?

For example, in my sprite I could hold all property of the sprite even if one property is not being used, let’s say an object that does not move around so it would have no speed which I could simple have a property saying that speed is disabled.

So i guess my real question is:

  • How should I structure my Sprite Class to have the best usage out of it ?

If you have a sample code to show I would appreciate aswell not really necessary, just for reference (also it doesnt need to be in c#).

Hope my question is not too confusing.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace MyGameTest
{
    class Sprite
    {
        public string AssetName;

        public Rectangle Size;

        private float mScale = 1.0f;

        public Vector2 Position = new Vector2(0, 0);

        public Vector2 Speed = new Vector2(0, 0);

        private Texture2D mSpriteTexture;

        public float Scale
        {
            get { return mScale; }
            set
            {
                mScale = value;
                Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
            }
        }

        public void LoadContent(ContentManager theContentManager, string theAssetName)
        {
            mSpriteTexture = theContentManager.Load<Texture2D>(theAssetName);
            AssetName = theAssetName;
            Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
        }

        public void Draw(SpriteBatch theSpriteBatch)
        {
            theSpriteBatch.Draw(mSpriteTexture, Position,
                                new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
                                Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0);
        } 
    }
}

I posted the following answer, which was chosen as the accepted answer and received 1 upvote:

I have found the concepts and examples in Johnathan Harbor’s book VB Game Programming with Direct X to be very useful when writing XNA and older MDX code. The book is OLD, and its in Visual Basic 6, but his examples do use encapsulation (since vb6 didn’t support inheritance) but they best illustrate the concept of building a basic ‘system’ through classes - I’d recommend browsing through it in the bookstore or library just to get some of the ideas: http://search.barnesandnoble.com/Visual-Basic-Game-Programming-with-DIRECTX/Jonathan-S-Harbour/e/9781931841252 — Thats not to say there are not any of these concepts well demonstrated on line or by other authors, but I know and can vouche for the ones in this book.

(This started as a comment but became too long pretty quickly)


Originally posted on Game Development — 1 upvotes (accepted answer). Licensed under CC BY-SA.

Offline Processing of POST Request

Someone asked on Stack Overflow:

I am developing an Application where I am submitting POST Requests to a .NET Web Service.

Current implementation is to process the request instantly and give response. In actual deployment, there will be huge amount of data that needs to be processed and thus the request must be processed offline.

What are the strategies that can have the task accomplished

Should I implement a Windows Service, or a scheduled task that invokes an application to perform the desired task.

I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:

If you have so much data it cannot be processed in real-time, I would probably setup the service to do the following:

ProcessRecordViaPost

  1. Create new record in “Queue” database with UniqueID, and all other info to be processed
  2. Return UniqueID to client immediatly

ReadRecordViaGet

  1. Check queue, if processed return data if not return status code (number of items in queue before it?)

I would also have a windows service that continually grabs the oldest item from the Queue, and processes it and moves on to the next oldest.

Notable comments

Nate (0 upvotes): If they are only going to be processed and deleted, then yeah, a database would be overkill. However, since you aren’t passing data back immediatly, how will your web service return data when the user finally comes back for it? It seems like you need to store the queue at least until the user makes the second request, no?


Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.

Processing large text files in .NET 3.5 c#

Someone asked on Stack Overflow:

I’m tasked with reading a large text file (around 150 MB), parsing it and displaying the records in a data grid. The file is delimited by parenthesis.

I’m accomplishing this by — in a separate thread — reading the entire file into memory, storing the information in a dataset and then binding the dataset to the data grid which sits on the main form in the original thread.

I have two questions/issues:

  1. Is this the best way to do it? Is reading a 150MB file into memory to large? What is the best practice when doing this type of work?

  2. The amount of memory that gets allocated for the process is HUGE.. which is understandable because I’m reading such a large file. But, the problem is it doesn’t get deallocated. So if I want to do process two files, more and more memory will get allocated. Until at some point the program will just crash. I’m guessing the dataset object is being referenced by something that’s preventing the memory from being allocated… is there anyway to determine what that object is? Is there a tool or a method I can use for this purpose?

Any help on this will be greatly appreciated. I’ve never in my coding career ever had to worry about memory management. Thanks.

I posted the following answer, which was chosen as the accepted answer and received 1 upvote:

  1. This is acceptable if you’r only ever reading a single file, and you don’t expect it to grow much beyond 150MB. The important factor here, is that users of your app have enough memory to open the file. 150Mb isn’t much, if you get to 150GB you’ll have problems.
  2. This is because you likely still have a reference to your file in memory somewhere. Likely due to the fact that you’re displaying it on screen.

If you need to load the whole thing into memory so users of your application can minipulate the file, your hands are tied. You might try streaming the records in as the user needs them. The TextReader and/or StreamReader classes are probably a good starting point if you want to go down that path.


Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.

signed letter b

Dad. Geek. Gamer. Software developer. Cloud user. Old Car enthusiast.  Blogger.


Top Posts


profile for Nate on Stack Exchange, a network of free, community-driven Q&A sites
a proud member of the blue team of 512KB club
Thoughts, opinions, and ideas shared here are my own. © 2026 Nate Bross.