Friday, March 13, 2015 by Nate Bross
Someone asked on Stack Overflow:
How to execute winzip command from MVC controller Action?
Command:
C:\Program Files (x86)\WinZip>WZZIP.EXE -ys2048000 Location Location
I posted the following answer, which was chosen as the accepted answer and received 1 upvote:
What you are asking, directly is possible with the System.Diagnostics.Process.Start(string, string) method. It would look something like this:
System.Diagnostics.Process.Start(
@"C:\Program Files (x86)\WinZip\WZZIP.EXE",
"-ys2048000 Location Location");
I’ve gone down this path and for simple things it is probably good enough. I’ve often found that there are usually more cool, useful things you can do interacting directly with the zip files. In that case, something like DotNetZip or SharpZip are probably good alternatives. I’ve used DotNetZip before, its very robust and highly performant.
Here’s a quick example from DotNetZip home page:
Here’s some C# code that creates a zip file.
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
Notable comments
Nate (0 upvotes): @SahilGupta I’m not sure what you mean, only licensed version. DotNetZip is Microsoft Public License (Ms-PL).
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Thursday, March 5, 2015 by Nate Bross
Someone asked on Stack Overflow:
I have a list MyGroups and a string ‘AllowedGroups’.
For example I have string in MyGroups.Name = “Admin Only” and AllowedGroups =“Admin Only, Normal Group”. I can’t understand why the following expression evaluates to false when it should be true:
model.MyGroups.Any(m => m.Name.Contains(AllowedGroups)
I posted the following answer, which was chosen as the accepted answer and received 6 upvotes:
I think what you need, based on the information you’ve provided, is the opposite of what you have.
Something like this:
var allowedGroupsArray = AllowedGroups.Split(',');
var result = model.MyGroups.Any(m => allowedGroupsArray.Contains(m.Name));
Specifically, using Array.Contains() inside the .Any() call should generate basically a WHERE ... IN type clause in your SQL.
Originally posted on Stack Overflow — 6 upvotes (accepted answer). Licensed under CC BY-SA.
Wednesday, July 2, 2014 by Nate Bross
Someone asked on Stack Overflow:
I´m on MVC and using KnockoputJS. I select the value from 2 select. In the first select i choose IDCompany, and the second select i choose IDSubsidiary.
I send the model in Json to JsonResult in the controller and I create a variable session and a cookie and save IDCompany in the Session variable and in the cookie with the same name.
I do the same with IDSubsidiary. Finally, I return to the ajax function (which call “Save” at first)
[HttpPost]
public JsonResult Save(ViewModel viewModel)
{
Session["IDCompany"] = viewModel.IDCompany.ToString();
Response.Cookies["IDCompany"].Value = viewModel.IDCompany.ToString();
Response.Cookies["IDCompany"].Expires = DateTime.Now.AddDays(1);
Session["IDSubsidiary"] = viewModel.IDSubsidiary.ToString();
Response.Cookies["IDSubsidiary"].Value = viewModel.IDSubsidiary.ToString();
Response.Cookies["IDSubsidiary"].Expires = DateTime.Now.AddDays(1);
return Json(true);
}
The problem is that after a while (30 mins approximately), i lose Session["IDCompany"] and Session["IDSubsidiary"] (becomes null). The problem can be that, for example, Session[“IDSubsidiary”] and Response.Cookies["IDSubsidiary"] has the same name?
I posted the following answer, which was chosen as the accepted answer and received 4 upvotes:
There are two reasons this could be happening. 1) The session is timing out, or 2) you are using “In Process” session state.
If the user sits on a page for thirty minutes, and then the value is gone the next time they refresh or go to another page, its likely a timeout problem. You could try increasing the sessionState timeout; however, you’ll probably start running into the issue described below. If you are determined to use Session variables, you should probably switch to a different state mode than “in process” which is the default.
If it is not timing out, the reason your value is lost is because “In Process” session state, goes away when the App Pool recycles. This can happen for a variety of reasons. You probably want to change your session state mode to State Server or SQL Server. This will keep your session data around between app pool recycles, but you will need to enable the “ASP.NET Session State Service” on the web server if you go the State Server route.
There are several state modes, each with different behaviors. You can read about them here on MSDN.
Notable comments
Nate (0 upvotes): @JohnSaunders That’s a fair point; I was assuming it was going away even with user activity (which should reset the timeout count down). I’ll update to include that too.
Originally posted on Stack Overflow — 4 upvotes (accepted answer). Licensed under CC BY-SA.
Tuesday, June 3, 2014 by Nate Bross
Someone asked on Stack Overflow:
I have a little bit of a problem with communicate between the controller and a view.
UploadFile (Class):
public class UploadFile
{
public string OrignialFilePath { get; set; }
public string FilteredFilePath { get; set; }
public string Name { get; set; }
public UploadFile(string x, string y, string z)
{
OrignialFilePath = x;
FilteredFilePath = y;
Name = z;
}
}
Files (Class):
public class Files
{
public List<UploadFile> list { get; set; }
public Files()
{
list = new List<UploadFile>();
}
}
Controller: (I get files with HTTP POST to this controller)
Files fileList = new Files();
foreach (var file in Files)
{
UploadFile fu = new UploadFile(file.x, file.y, file.z);
fileList.list.Add(fu);
}
return RedirectToAction("Result");
Result: (Strongly-typed view)
@model IEnumerable<SelectorITSelectorIT.Models.Files>
@{
ViewBag.Title = "Result";
}
<h2>SelectorIT - Result</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
</tr>
@foreach ( var item in Model) {
<tr>
<td>
@item.list ?????
</td>
</tr>
}
</table>
In the foreach var item in model
When i write @item.list i cant go to the files within some index of the list ( i have there UploadFile instance).
I need in the foreach statement : foreach var item in model.list but it doesn’t let me, how can i do it?
My Main goal is to Simply display in a table details about each UploadFile in the list of the model(“Files”).
How can i do it ?
Yes, I you need to use the .list property that you defined in Files and you need to change your view model to simply
@model SelectorITSelectorIT.Models.Files
...
@foreach (var item in Model.list) {
<tr>
<td>@item.Name</td>
</tr>
}
On the other hand, if you really want an IEnumerable of Files, you need to rewrite your loop similar to this:
@foreach (var item in Model) {
foreach(var file in item.list)
{
<tr>
<td>@file.Name</td>
</tr>
}
}
But based on your question, I’m thinking you really just want a model of Files since it already has the list of UploadFiles in it.
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Friday, May 30, 2014 by Nate Bross
Someone asked on Stack Overflow:
I have this table
ID Name City ... more columns
----------------------------------------------
1 Nate Boston ...
2 John Boston ...
2 John Boston ...
3 Sam Austin ...
(for reasons beyond my control, ID is duplicated in some cases)
and I have an entity framework model setup for this, in general its working pretty well. I am having an issue while trying to get a unique list.
var result = db.table.GroupBy(t => new
{
ID = t.ID,
Name = t.Name,
City = t.City
}).Select(g => g.Key)
Problem is, this query returns the following:
ID Name City
-----------------------------
1 Nate Boston
2 John Boston
2 John Boston
3 Sam Austin
I thought I was going crazy, so I fired up LinqPad, ran the same query and got my expected results:
ID Name City
-----------------------------
1 Nate Boston
2 John Boston
3 Sam Austin
I realized that with LinqPad I was connected to my database with Linq-To-SQL, not using the EntityFramework providers for LinqPad. When I connect LinqPad through my assembly, using EntityFramework, I get the same results as in my real project.
What am I missing that is causing Entity Framework and Linq-To-SQL to return different results for the same query and how can I get the same results as Linq-To-SQL?
I should point out that in LinqPad, if I remove the .Select(g => g.Key); The results are displayed in the quick view as expected (Key is unique per grouping, and the 2, John, Boston record has two child elements).
For reference, the generated SQL.
This is the generated SQL from Linq-To-SQL:
SELECT [t0].[ID], [t0].[Name], [t0].[City]
FROM [Table] AS [t0]
GROUP BY [t0].[ID], [t0].[Name], [t0].[City]
This is the generated SQL from Entity Framework:
SELECT
1 AS [C1],
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
[Extent1].[City] AS [City]
FROM (SELECT
[Table].* -- I changed this to .* because EF code listed all column in table explicitly
FROM [dbo].[Table] AS [Table]) AS [Extent1]
I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:
@Gusman lead me to the solution. To the EntityKey issue got me thinking that it must be an Entity Framework thing having something to do with the comparison of the ID going wrong since there are duplicates.
I re-wrote the query as follows, using Linq-To-Objects and I do get the expected results. The key here is to perform the .GroupBy(...) after the .ToList() so the values are compared in memory, where C# rules are used instead of database or entity framework comparison rules.
var result = db.table
.Select(t =>
{
ID = t.ID,
Name = t.Name,
City = t.City
}) // project only used columns, to reduce data from db => web server
.ToList() // convert from Linq-To-Entities, to Linq-To-Objects
.GroupBy(t => new
{
ID = t.ID,
Name = t.Name,
City = t.City
})
.Select(g => g.Key)
I’m presuming this is some sort of Entity Framework optimization (that Linq-To-SQL does not do) that in my case of duplicate IDs is back firing.
Since I needed to enumerate all returned data anyway, the .ToList() call is not so bad for me. My table is pretty wide though, so I performed the additional .Select(t => new { ... }) to reduce the number of columns returned from the database server, since I wont benefit from lazy loading after the .ToList().
Notable comments
Nate (0 upvotes): Thanks man, your comments were really helpful and lead me to the solution.
Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.
Wednesday, May 28, 2014 by Nate Bross
Someone asked on Stack Overflow:
I need to change an image in an openxml word document. To do this I thought I could simply open the .docx file using ZipArchive and replace the current image word/media/image1.jpg with the new image and rezip it up. The one caveat is that I would like to do this all in memory if possible.
I am using ZipArchive from System.IO.Compression and can open the docx and find the image without a problem. The problem arise when i try to replace the file and regenerate the zip all in memory.
This will run on a web server and might have max 10-20 files happening at the same time and I will have everything as byte[], which is the reason i wanted to keep it all in memory. I would also be interested to know if people think I should just write it out to the disk.
Update: The actual docx will be uploaded from the user and the image i am replacing will be stored as a binary field in a database.
I would recommend you look into using DotNetZip. It is much more robust than the built-in capabilities of the framework. It also has a pretty simple to grasp API.
I see no reason you need to write to disk. You should be able to open the file from disk, make the modifications, and then send that down as part of the response.
While using a byte[] is good, as that is what the data is, you might want to look into using one of the stream classes, MemoryStream comes to mind as a nice API for dealing with binary data in memory.
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Tuesday, May 27, 2014 by Nate Bross
Someone asked on Stack Overflow:
I want have my azure . NET web application upload a file, manipulate it and then download the changed version.
Should I use blob storage? I don’t actually need to store the data in the file.
Should I use blob storage?
That depends on what your requirements are.
I don’t actually need to store the data in the file.
Given this fact, you probably don’t need to use blog storage.
You could simply do something like this:
var postedFile = Request.Files[0] as HttpPostedFileBase;
var stream = new MemoryStream();
postedFile.InputStream.CopyTo(stream);
// work with MemoryStream
...
//return your file which could be different based on mvc, web forms or whatever
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Tuesday, May 27, 2014 by Nate Bross
Someone asked on Stack Overflow:
I have a database, that contains an tinyint column with “1” or “0” for marking as “yes” or “no”.
In my razor view I want to Show this in a ListBox. When reading rows out of the database, I want to preselect the corresonding item in the ListBox.
Code here is simplified:
var mItems = new List<SelectListItem>{
new SelectListItem { Value="1", Text="Yes"},
new SelectListItem { Value="0", Text="No"}
};
int mIsProofed = 0;
// This doesn´t preselect my item:
mItems.Select(x => x.Value == mIsProofed.ToString());
:
@Html.ListBox("mylistbox", mItems)
Any ideas how to resolve this?
I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:
You need to set the Selected property on the SelectListItem.
I’d update your code to be similar to this:
var selectedItem = mItems.FirstOrDefault(x => x.Value == mIsProofed.ToString());
if(selectedItem != null)
{
selectedItem.Selected = true;
}
This will find the item you wish to select, and update its selected property if it is found, otherwise it does not modify anything.
The .Select() method you are using is used to perform a projection on the list, in other words it is more like the select command in SQL, where you specify a subset (or the full set) of data.
Originally posted on Stack Overflow — 2 upvotes (accepted answer). Licensed under CC BY-SA.
Wednesday, May 21, 2014 by Nate Bross
Someone asked on Stack Overflow:
I’ve been following a blog post from Brady Gaster to create a Azure worker role to create a JSON endpoint.
All is going well, create a worker role and deployed to Azure with no problem except it returns XML instead of JSON.
It returns the following result:
<ArrayOfMessage xmlns="http://schemas.datacontract.org/2004/07/Backend.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Message><Id>5de2ed85-1eb1-4306-aace-645ea9202f26</Id></Message></ArrayOfMessage>
While I expected just a GUID something like:
{
Id: '5de2ed85-1eb1-4306-aace-645ea9202f26'
}
Not sure whats wrong, followed the code examples from the blog post. Unfortunately his codesamples weren’t available for download so I can’t compare specific configuration…
Any ideas?
Are you sending the JSON accept header with your request?
Different clients will send different accept headers by default, and you may need to override them to get the type of response that you’re looking to get.
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.
Thursday, May 8, 2014 by Nate Bross
Someone asked on Stack Overflow:
Cutting out a lot of irrelevant information, the basics are that I have a web address like so:
https://dinglydangs.com/download.dll?request=file&name=dunderdata.csv
I am using WebClient.DownloadFile to, well, download the file. I need to know if, because it is an https link, this method is using an HTTPS connection to download the file. If not, what steps would I need to take to ensure an HTTPS connection is used?
Possibly relevant: The link itself is sent to me in an e-mail. No actual authentication is required, I simply navigate to the link and the file downloads.
I posted the following answer, which was chosen as the accepted answer and received 1 upvote:
WebClient will use the protocol specified in the Uri you pass the download method. You don’t have to do anything special to make this happen.
You can use a tool like Fiddler to verify this, by checking the connections going out from your machine.
Notable comments
Nate (0 upvotes): So, I said uri and the method accepts address both are a pointer to the online resource you want to download. As long the online resource link is https, the connection will be over https…
Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.