Pdf's fields should remain editable using itextsharp in asp.net - asp.net

I have a fillable pdf. In which i have few textboxes.
I fill these fields by using following code(itextsharp).
DataTable dt = new DataTable();
String pdfPath1 = Server.MapPath("pdfs\\transmittal2.pdf");
if (File.Exists(pdfPath1))
{
dt = objClsTransmittal.GetTransmittal(jobid, cid);
String comment = "Correspondence generated for " + dt.Rows[0]["Recipient"].ToString();
var formfield = PDFHelper.GetFormFieldNames(pdfPath1);
formfield["DocDate"] = DateTime.Now.ToLongDateString();
formfield["Address1"] = dt.Rows[0]["Company"].ToString();
formfield["Address2"] = dt.Rows[0]["Address1"].ToString();
formfield["PropertyAddress"] = dt.Rows[0]["PropertyAddress"].ToString();
formfield["Job"] = dt.Rows[0]["JobID"].ToString();
formfield["Name"] = dt.Rows[0]["Recipient"].ToString();
formfield["CityStateZip"] = dt.Rows[0]["address2"].ToString();
formfield["E-mail"] = dt.Rows[0]["Email"].ToString();
var pdfcontent = PDFHelper.GeneratePDF(pdfPath1, formfield);
PDFHelper.ReturnPDF(pdfcontent, "Transmittal.pdf");
}
Currently its downloded as read only pdf.
when this pdf gets downloaded, i want that all fields still remain fillable, with the text i have filled in pdf. So that i can edit the text.
I'm looking forward for your replies.
Thanks.
EDIT
PdfHelper is my custom class. In which i have used following code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}

Your code line
stamper.FormFlattening = true;
instructs iTextSharp to flatten the form fields, i.e. to integrate them into the page content and remove the form field annotations.
As you want to keep the form fields as editable fields, don't flatten the form.

Error: Cannot convert type in PDFHelper.cs
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields) //ERROR: 'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'
{
fields.Add(entry.Key.ToString(), string.Empty);
}
reader.Close();
return fields;
}
'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'

Related

How to Create and Delete edge properties (Titan 1.0) using c# in .net mvc?

I was using Titan 1.0 with gremlin server to create and delete vertex. I want to implement this logic in my .net project. I wonder if there is any pre build plugin for titan and gremlin server in asp.net?
Currently i'm directly using command prompt to create and delete the required vertices and edges. how can I implement it in my .net MVC project?
I've created one class in my project for interacting with Gremlin server using REST API. you can make small changes to make it work for you.
Source: https://askgif.com/blog/145/how-to-create-and-delete-edge-properties-titan-1-0-using-c-in-net-mvc/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using RestSharp;
using urNotice.Common.Infrastructure.Common.Config;
using urNotice.Common.Infrastructure.Common.Constants;
using urNotice.Common.Infrastructure.Common.Enum;
using urNotice.Common.Infrastructure.commonMethods;
using urNotice.Common.Infrastructure.Model.urNoticeModel.DynamoDb;
using urNotice.Services.NoSqlDb.DynamoDb;
namespace urNotice.Services.GraphDb
{
public class GremlinServerGraphEdgeDb : IGraphEdgeDb
{
private delegate Dictionary<string, string> AddEdgeAsyncDelegate(string userName, string graphName, Dictionary<string, string> properties);
public Dictionary<string, string> AddEdge(string userName, string graphName, Dictionary<string, string> properties)
{
string url = TitanGraphConfig.Server;
var response = CreateEdge(graphName, properties, url);
// add edge to dynamodb.
var edgeDetail = new OrbitPageEdgeDetail
{
url = url,
edgeId = response[TitanGraphConstants.Id],
graphName = graphName,
properties = properties
};
IDynamoDb dynamoDbModel = new DynamoDb();
dynamoDbModel.UpsertOrbitPageEdgeDetail(edgeDetail, userName, properties[EdgePropertyEnum._inV.ToString()], properties[EdgePropertyEnum._outV.ToString()]);
//Adding edgeDetail for faster query.
//dynamoDbModel.UpsertOrbitPageEdgeForQueryDetail(edgeDetail, userName, properties[EdgePropertyEnum._inV.ToString()], properties[EdgePropertyEnum._outV.ToString()]);
return response;
}
public Dictionary<string, string> DeleteEdge(string inV, string outV, string label)
{
string url = TitanGraphConfig.Server;
IDynamoDb dynamoDbModel = new DynamoDb();
string uniqueKey = OrbitPageUtil.GenerateUniqueKeyForEdgeQuery(inV, label, outV);
var edgeInfo = dynamoDbModel.GetOrbitPageCompanyUserWorkgraphyTable(
DynamoDbHashKeyDataType.EdgeDetail.ToString(),
uniqueKey,
null);
if (edgeInfo == null)
return null;
var response = DeleteEdgeNative(TitanGraphConfig.Graph, edgeInfo.CompareId, url);
dynamoDbModel.DeleteOrbitPageCompanyUserWorkgraphyTable(edgeInfo);
//Deleting Edge detail creating for only query purpose.
//string uniqueKey = OrbitPageUtil.GenerateUniqueKeyForEdgeQuery(inV, label, outV);
//edgeInfo = dynamoDbModel.GetOrbitPageCompanyUserWorkgraphyTable(
// DynamoDbHashKeyDataType.EdgeDetail.ToString(),
// uniqueKey,
// null);
//if(edgeInfo!=null)
// dynamoDbModel.DeleteOrbitPageCompanyUserWorkgraphyTable(edgeInfo);
return response;
}
public Dictionary<string, string> AddEdgeAsync(string userName, string graphName, Dictionary<string, string> properties)
{
var addEdgeAsyncDelegate = new GremlinServerGraphEdgeDb.AddEdgeAsyncDelegate(AddEdge);
addEdgeAsyncDelegate.BeginInvoke(userName, graphName, properties, null, null);
return null;
}
private Dictionary<String, String> CreateEdge(string graphName, Dictionary<string, string> properties, string url)
{
var uri = new StringBuilder(url + "/?gremlin=");
//http://localhost:8182/?gremlin=g.V(8320).next().addEdge("Using",g.V(12416).next(),"Desc","Item used by Person","time",12345)
string graphProperties = string.Empty;
//_outV must be the first parameter
graphProperties += "'" + properties[EdgePropertyEnum._label.ToString()] + "', g.V(" + properties[EdgePropertyEnum._inV.ToString()] + ").next() ,";
foreach (KeyValuePair<string, string> property in properties)
{
if (property.Key == EdgePropertyEnum._inV.ToString() || property.Key == EdgePropertyEnum._outV.ToString() || property.Key == EdgePropertyEnum._label.ToString())
{
//do nothing.. May be in future we will write logic here.
}
else
{
if (property.Key == EdgePropertyEnum.PostedDateLong.ToString() || property.Key == EdgePropertyEnum.SalaryAmount.ToString())
graphProperties += "'" + property.Key + "', " + property.Value + " ,";
else
graphProperties += "'" + property.Key + "', '" + property.Value + "' ,";
}
}
if (!string.IsNullOrEmpty(graphProperties))
{
graphProperties = graphProperties.Substring(0, graphProperties.Length - 2);
}
uri.Append("g.V(" + properties[EdgePropertyEnum._outV.ToString()] + ").next().addEdge(" + graphProperties + ");");
var client = new RestClient(uri.ToString());
var request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", "", ParameterType.RequestBody);
var res = client.Execute(request);
var content = res.Content; // raw content as string
dynamic jsonResponse = JsonConvert.DeserializeObject(content);
var response = new Dictionary<String, String>();
response["status"] = "200";
response["CreateEdgeStatus"] = "200";
response[TitanGraphConstants.Id] = jsonResponse.result.data[0].id;
response[TitanGraphConstants.RexsterUri] = url;
return response;
}
private Dictionary<String, String> DeleteEdgeNative(string graphName, string edgeId, string url)
{
var uri = new StringBuilder(url + "/?gremlin=");
//var uri = new StringBuilder(url + "/graphs/" + graphName + "/edges/" + edgeId);
//http://localhost:8182/?gremlin=g.E('odxqo-6f4-2hat-9kw').drop()
uri.Append("g.E('" + edgeId + "').drop();");
var client = new RestClient(uri.ToString());
var request = new RestRequest();
request.Method = Method.GET;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", "", ParameterType.RequestBody);
var res = client.Execute(request);
var content = res.Content; // raw content as string
dynamic jsonResponse = JsonConvert.DeserializeObject(content);
var response = new Dictionary<String, String>();
response["status"] = "200";
response["DeleteEdgeStatus"] = "200";
//response[TitanGraphConstants.Id] = jsonResponse.result.data[0].id;
//response[TitanGraphConstants.RexsterUri] = url;
return response;
}
}
}
comment if you face any issue in the class.

Convert data to JSON format

i have used the Newtonsoft.Json for converting data into json format.
I have write the below code:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
string JSONString = string.Empty;
JSONString = "{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}";
return JSONString;
}
So it gives me the below output:
But i want the output like :
{"mydata":[{"id":125},{"id":137},{"id":249},{"id":201},{"id":124},
{"id":173},{"id":160},{"id":153},{"id":146},{"id":168}]}
So how can i convert to it from xml to json. ?
I run your solution in a console application and I can clearly see the problem. If you avoid building json manually, the problem will go away. As I don't have database, I have added my data rows manually. Hope that will help.
using Newtonsoft.Json;
using System;
using System.Data;
namespace Test
{
class MyDataContainer
{
public DataTable mydata { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write(DataTableToJSONWithJSONNet());
Console.Read();
}
static string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
dt.Rows.Add(1);
dt.Rows.Add(2);
MyDataContainer cont = new MyDataContainer();
cont.mydata = dt;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(cont);
//to see your attempt uncomment the blow lines
//Console.Write("{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}");
//Console.WriteLine();
return JSONString;
}
}
}
Looking into your codes, you are already declared that your output is type of JSON, so on the response data it will return a JSON string.
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
And you also declared that this is a ScriptMethod. My thought is you are testing your app by running your code and accessing the url of the web service - for example http://localhost/test.asmx and clicking the invoke button on your DataTableToJSONWithJSONNet method. This approach will really display JSON result enclosed on XML format. The best way to test your own code is to invoke the web service using something like jQuery Ajax or equivalent (client scripts).
You can change your code to something like this to achieve the output you are looking for:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyResponse DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
MyResponse result = new MyResponse();
result.mydata = dt;
return result;
}
class MyResponse
{
private object _mydata;
public object mydata { get { return this._mydata; } set { this._mydata = value; } }
public MyResponse() { }
}

Render Full View as String in ASP.NET

I have found this code to render a partial view as a string:
public static string RenderPartialToString(string controlName, object viewData)
{
ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };
viewPage.ViewData = new ViewDataDictionary(viewData);
viewPage.Controls.Add(viewPage.LoadControl(controlName));
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
viewPage.RenderControl(tw);
}
}
return sb.ToString();
}
However I need to render a full view as a string (which contains ViewData).
What is the best way to do this?
Rendering a full view as string:
private string RenderViewToString(string viewName, object model=null)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
if (model != null)
ViewData.Model = model;
// you can pass in additional arguments to this function
// and manipulate the ViewData further if you need to
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
Use like this, if you want to render a page without model:
var text = RenderViewToString("Index");
and like this, if you want to render a page with a model
var text = RenderViewToString("OtherPage", model);

How to retrieve logged user image from AD?

I had my code to retrieve logged user details , every thing is OK but
i cannot retrieve the user image .
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", Environment.UserName);
//SearchResult findUser = searcher.FindOne();
foreach (SearchResult findUser in searcher.FindAll())
{
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
string userName = user.Properties["displayName"].Value.ToString();
string departement = user.Properties["Department"].Value.ToString();
string title = user.Properties["title"].Value.ToString();
string[] rt = new string[] { Login, userName, Email, Mobile };
Lbl_User.Text = userName;
Lbl_Administrative.Text = departement;
Lbl_Position.Text = title;
}
}
I've just taken your code and made a method out of it just to retrieve the image. You would need to refactor it, to either get only the byte[] or thw whole image.
//add this
using System.Drawing;
static Image GetPhotoFromAD(string userName)
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", userName);
//SearchResult findUser = searcher.FindOne();
foreach (SearchResult findUser in searcher.FindAll())
{
if (findUser != null)
{
byte[] photodata = findUser.Properties["jpegPhoto"].Value as byte[];
using (MemoryStream str = new MemoryStream(photodata))
{
return Bitmap.FromStream(str);
}
}
}
}
If you only want the raw data, the important bit is byte[] photodata = user.Properties["jpegPhoto"].Value as byte[];
The binary image should be stored in property called thumbnailPhoto.
var photo = user.Properties["thumbnailPhoto"];
if (photo != null) {
byte[] buffer = (byte[])photo.Value;
//var bitmap = new Bitmap(new MemoryStream(buffer, false));
//bitmap.Save(#"c:\test.bmp");
}
Now, given the fact that you tagged question as asp.net you'll have to write generic handler (.ashx) for retrieving the image. This handler should write content of
photo.Value
into response output stream and set content type to image/bmp
In your control/page just reference the handler like
<img src="/GenericHandler.ashx" alt="My image" />

saving a pdf to a sql database using itextsharp

I'm using this tutorial https://web.archive.org/web/20211020001747/https://www.4guysfromrolla.com/articles/030211-1.aspx that’s uses a PDF template, lets the user input fields using textbox's. The file downloads onto the client’s pc but I would like to save a copy of the file into a sql database also or just save the file in the database instead of both.
protected void btnGeneratePDF_Click(object sender, EventArgs e)
{
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/fw9.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = txtName.Text;
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = txtBusinessName.Text;
if (rblTaxClassification.SelectedValue != null)
{
var formFieldName = string.Format("topmostSubform[0].Page1[0].c1_01[{0}]", rblTaxClassification.SelectedIndex);
formFieldMap[formFieldName] = (rblTaxClassification.SelectedIndex + 1).ToString();
}
if (chkExemptPayee.Checked)
formFieldMap["topmostSubform[0].Page1[0].c1_01[7]"] = "8";
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = txtAddress.Text;
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = txtCityStateZIP.Text;
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = txtAccountNumbers.Text;
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Acme Website\n123 Anywhere Lane\nSpringfield, USA";
// SSN
if (!string.IsNullOrEmpty(txtSSN1.Text))
{
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = txtSSN1.Text;
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = txtSSN2.Text;
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = txtSSN3.Text;
}
else if (!string.IsNullOrEmpty(txtEIN1.Text))
{
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = txtEIN1.Text;
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = txtEIN2.Text;
}
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
FileStream fs = new FileStream(pdfPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = "Completed-W9132.pdf";
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "application/pdf";
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
App_code/pdfHelper.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
// See http://stackoverflow.com/questions/4491156/get-the-export-value-of-a-checkbox-using-itextsharp/
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
// /D is for the "down" appearances.
// if there are normal appearances, one key will be "Off", and the other
// will be the export value... there should only be two.
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/', so remove it!
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
}
The parts of the tutorial you're looking for in that case are right here:
Response.ContentType = "application/pdf";
Response.BinaryWrite(output.ToArray());
When saving a "file" to a database you essentially care about two (maybe three) things:
The byte array of the file contents
The type of the file
(Maybe a name for the file)
Since the tutorial concludes with two of these things (above), the type and the data, you can store these two things into your database however you need to store them. This depends on the database you're using, how you access that database, etc. Essentially to store these two things you just need a text column (varchar?) and a binary (or "blob") column (varbinary?).
The only difference is that instead of setting the type as a header in an HTTP response and writing the bytes to that HTTP response, you're using both of them as values in your database. Everything else is the same.

Resources