private void ReplyError(HttpStatusCode statusCode, string text, HttpResponse response) { response.StatusCode = (int)statusCode; response.ContentType = "text/html"; response.Write(String.Format("<html><title>MovieInfo : ERROR</title><body><p>{0}</p></body></html>", text)); for (int i = 0; i < 85; ++i) response.Write(" "); }
protected HttpContext SetupFakeHttpContext() { var httpRequest = SetUpHttpRequest(); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); return new HttpContext(httpRequest, httpResponse); }
public static void WriteJsonResponse(HttpResponse response, object model) { var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(model); response.Write(json); response.End(); }
public void Save(string ipAddress, HttpContext context, HttpRequest request, HttpResponse response) { ELSLog esLog = new ELSLog(); esLog.ElsIpaddress = ipAddress; /* var x = request.Path; x = Getapifunction(x); switch (request.HttpMethod) { case "GET" : x = "SEE " + x; break; case "POST": x = "SENT " + x; break; }*/ // if (x == "/api/contact") // { // x = "sendqueue";} esLog.ElsRequest = "[" + DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss zz") + "]" + " \"" + request.HttpMethod + " " + request.Path + "\" " + response.StatusCode + " " + request.TotalBytes + " \"" + request.UrlReferrer + "\" " + "\"" + request.UserAgent + "\"" + " " + request.Form; /* if (HttpContext.Current.Session != null) { // context.Session[Userlog] = esLog; Session[Userlog] = esLog; }*/ context.Items[Userlog] = esLog; }
public static void DeleteCookie(HttpRequest Request, HttpResponse Response, string name, string value) { HttpCookie cookie = new HttpCookie(name); cookie.Expires = DateTime.Now.AddDays(-1D); cookie.Value = value; Response.AppendCookie(cookie); }
private void DoPost(HttpRequest httpRequest, HttpResponse httpResponse) { Dictionary<string, Stream> files = httpRequest.Files.AllKeys.ToDictionary(n => n, n => httpRequest.Files[n].InputStream); DirectRequest[] requests = new DirectRequestsBuilder().Build(new StreamReader(httpRequest.InputStream, httpRequest.ContentEncoding), httpRequest.Form, files); var responses = new DirectResponse[requests.Length]; for(int i = 0; i < requests.Length; i++) { responses[i] = new DirectHandler(_objectFactory, _metadata).Handle(requests[i]); } using(var textWriter = new StreamWriter(httpResponse.OutputStream, httpResponse.ContentEncoding)) { if(requests[0].Upload) { httpResponse.ContentType = "text/html"; textWriter.Write("<html><body><textarea>"); SerializeResponse(responses, textWriter); textWriter.Write("</textarea></body></html>"); } else { httpResponse.ContentType = "application/json"; SerializeResponse(responses, textWriter); } } }
public void SendEnvelope(HttpResponse httpResponse) { httpResponse.ContentEncoding = Encoding.UTF8; httpResponse.ContentType = SoapConstants.XmlContentType; SendEnvelope(httpResponse.OutputStream); }
/// <summary> /// Creates a new RouteContext /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> /// <param name="applicationPath">The application path.</param> /// <param name="contextItems">The context items.</param> public RouteContext(IRequest request, HttpResponse response, string applicationPath, IDictionary contextItems) { this.request = request; this.response = response; this.applicationPath = applicationPath; this.contextItems = contextItems; }
public static void Do302Redirect(HttpResponse response, string targetURL) { response.StatusCode = 0x12e; response.StatusDescription = "302 Moved Permanently"; response.RedirectLocation = targetURL; response.End(); }
public CookieHelper() { HttpContext context = HttpContext.Current; _request = context.Request; _response = context.Response; }
public void Indexer () { HttpResponse response = new HttpResponse (Console.Out); HttpCacheVaryByContentEncodings encs = response.Cache.VaryByContentEncodings; encs ["gzip"] = true; encs ["bzip2"] = false; Assert.IsTrue (encs ["gzip"], "gzip == true"); Assert.IsFalse (encs ["bzip2"], "bzip2 == false"); bool exceptionCaught = false; try { encs [null] = true; } catch (ArgumentNullException) { exceptionCaught = true; } Assert.IsTrue (exceptionCaught, "ArgumentNullException on this [null] setter"); exceptionCaught = false; try { bool t = encs [null]; } catch (ArgumentNullException) { exceptionCaught = true; } Assert.IsTrue (exceptionCaught, "ArgumentNullException on this [null] getter"); }
public ContextResponse(HttpContext context) { if (context == null) throw new ArgumentNullException("context"); _response = context.Response; _server = context.Server; }
public GoogleOIDC(HttpRequest request, HttpResponse response) { this.request = request; this.response = response; this.accessCode = request["code"]; }
private void Real(HttpResponse response, HttpRequest request) { if (File.Exists(request.PhysicalPath)) { FileInfo file = new System.IO.FileInfo(request.PhysicalPath); response.Clear(); response.AddHeader("Content-Disposition", "filename=" + file.Name); response.AddHeader("Content-Length", file.Length.ToString()); string fileExtension = file.Extension.ToLower(); switch (fileExtension) { case ".mp3": response.ContentType = "audio/mpeg3"; break; case ".mpeg": response.ContentType = "video/mpeg"; break; case ".jpg": response.ContentType = "image/jpeg"; break; case ".bmp": response.ContentType = "image/bmp"; break; case ".gif": response.ContentType = "image/gif"; break; case ".doc": response.ContentType = "application/msword"; break; case ".css": response.ContentType = "text/css"; break; case ".html": response.ContentType = "text/html"; break; case ".htm": response.ContentType = "text/html"; break; case ".swf": response.ContentType = "application/x-shockwave-flash"; break; case ".exe": response.ContentType = "application/octet-stream"; break; case ".inf": response.ContentType = "application/x-texinfo"; break; default: response.ContentType = "application/octet-stream"; break; } response.WriteFile(file.FullName); response.End(); } else { response.Write("File Not Exists"); } }
//public static void DisableMasterPageStamp(Page page) //{ // Validate.NotNull(page, "page"); // if (page.Master != null) // { // Control ctrl = page.Master.FindControl(DoubleSubmitStamp.MasterPageControlName); // if (ctrl != null) // ((DoubleSubmitStamp) ctrl).RenderStamp = false; // } //} public static void MakePageExpired(HttpResponse response) { Validate.NotNull(response, "response"); response.Expires = 0; response.Cache.SetNoStore(); response.AppendHeader("Pragma", "no-cache"); }
/// <summary> /// Invokes the appropriate service handler (registered using a ServiceAttribute) /// </summary> public void InvokeServiceHandler(Message request, Message response, HttpSessionState session, HttpResponse httpresponse) { if (request.Type.Equals(this.Request)) { try { Message temp_response = response; Object[] parameters = new Object[] { request, temp_response }; Object declaringTypeInstance = Activator.CreateInstance(this.MethodInfo.DeclaringType); this.MethodInfo.Invoke(declaringTypeInstance, parameters); temp_response = (Message)parameters[1]; temp_response.Type = this.Response; temp_response.Scope = request.Scope; temp_response.Version = request.Version; temp_response.RequestDetails = request.RequestDetails; Logger.Instance.Debug("Invoked service for request: " + request.Type); Dispatcher.Instance.EnqueueOutgoingMessage(temp_response, session.SessionID); } catch (Exception e) { String err = ""; err+="Exception while invoking service handler - " + this.MethodInfo.Name + " in " + this.MethodInfo.DeclaringType.Name + "\n"; err += "Request Message - " + request.Type + "\n"; err += "Response Message - " + response.Type + "\n"; err += "Message - " + e.Message + "\n"; err += "Stacktrace - " + e.StackTrace + "\n"; Logger.Instance.Error(err); } } }
//defaultfile is under userpath public static void GetImageFromFile(string filename,string defaultfile,HttpResponse response) { if (!File.Exists(filename)) { string userdatapath = Functions.GetAppConfigString("UserDataPath", ""); filename = userdatapath + "\\"+defaultfile; } System.IO.FileStream fs = null; System.IO.MemoryStream ms = null; try { fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); ms = new System.IO.MemoryStream(buffer); response.ClearContent(); response.BinaryWrite(ms.ToArray()); ms.Close(); } finally { fs.Dispose(); ms.Dispose(); } }
internal OutputStream(HttpResponse response, Action start, Action faulted) : base(response.OutputStream) { _response = response; _start = start; _faulted = faulted; }
/// <summary> /// Parses specified url and returns a RouteData instance. /// Then, for example, you can do: routeData.Values["controller"] /// </summary> public static RouteData GetRouteData(this RouteCollection routeCollection, string url, string queryString = null) { var request = new HttpRequest(null, url, queryString); var response = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(request, response); return RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); }
/// <summary> /// Initializes a new instance of the <see cref="ResponseAdapter"/> class. /// </summary> /// <param name="response">The response.</param> /// <param name="currentUrl">The current URL.</param> /// <param name="urlBuilder">The URL builder.</param> /// <param name="serverUtility">The server utility.</param> /// <param name="routeMatch">The route match.</param> /// <param name="referrer">The referrer.</param> public ResponseAdapter(HttpResponse response, UrlInfo currentUrl, IUrlBuilder urlBuilder, IServerUtility serverUtility, RouteMatch routeMatch, string referrer) : base(currentUrl, urlBuilder, serverUtility, routeMatch, referrer) { this.response = response; }
public CachedFile(FileResponse response, HttpResponse gzippedResponse) { Response = response; LastModified = response.LastModified; ContentType = response.ContentType; GZippedResponse = gzippedResponse; }
/// <summary> /// Mock an <see cref="HttpContext"/> object with the base URL, together with appropriate /// host headers so that code that doesn't operate under an <see cref="HttpContext"/> /// can still use one in replacement. /// </summary> public static HttpContext FakeHttpContext(this HttpContext realContext) { var baseUrl = realContext.GetPublicFacingBaseUrl(); var request = new HttpRequest(string.Empty, baseUrl.ToString(), string.Empty); var response = new HttpResponse(null); return new HttpContext(request, response); }
private static void SendNotFoundResponse(string message, HttpResponse httpResponse) { httpResponse.StatusCode = (int) HttpStatusCode.NotFound; httpResponse.ContentType = "text/plain"; httpResponse.Write(message); httpResponse.End(); // This terminates the HTTP processing pipeline }
void Download(HttpResponse resp, GUIDEx fileID) { lock (this) { if (resp != null) { string fullFileName = null, contentType = null; byte[] data = this.workDownloadService.Download(fileID, out fullFileName, out contentType); if (data != null && data.Length > 0) { resp.Buffer = true; resp.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fullFileName, System.Text.Encoding.UTF8)); resp.ContentEncoding = Encoding.GetEncoding("gb2312");//设置输出流为简体中文 resp.ContentType = contentType;//"application/OCTET-STREAM"; // resp.BufferOutput = true; resp.BinaryWrite(data); resp.Flush(); resp.End(); } else { resp.Write("文件不存在!" + fileID); } } } }
public void ExportToCSV(DataTable dataTable, HttpResponse response) { response.Clear(); response.Buffer = true; response.AddHeader("content-disposition", "attachment;filename=DataTable.csv"); response.Charset = ""; response.ContentType = "application/text"; StringBuilder sb = new StringBuilder(); for (int k = 0; k < dataTable.Columns.Count; k++) { //add separator sb.Append(dataTable.Columns[k].ColumnName + ','); } //append new line sb.Append("\r\n"); for (int i = 0; i < dataTable.Rows.Count; i++) { for (int k = 0; k < dataTable.Columns.Count; k++) { //add separator sb.Append(dataTable.Rows[i][k].ToString().Replace(",", ";") + ','); } //append new line sb.Append("\r\n"); } response.Output.Write(sb.ToString()); response.Flush(); response.End(); }
// This copy constructor is used by the granular request validation feature. Since these collections are immutable // once created, it's ok for us to have two collections containing the same data. internal HttpHeaderCollection(HttpHeaderCollection col) : base(col) { _request = col._request; _response = col._response; _iis7WorkerRequest = col._iis7WorkerRequest; }
public void ExportToExcel(DataTable dataTable, HttpResponse response) { // Create a dummy GridView GridView GridView1 = new GridView(); GridView1.AllowPaging = false; GridView1.DataSource = dataTable; GridView1.DataBind(); response.Clear(); response.Buffer = true; response.AddHeader("content-disposition", "attachment;filename=DataTable.xls"); response.Charset = ""; response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); for (int i = 0; (i <= (GridView1.Rows.Count - 1)); i++) { // Apply text style to each Row GridView1.Rows[i].Attributes.Add("class", "textmode"); } GridView1.RenderControl(hw); // style to format numbers to string string style = "<style> .textmode{mso-number-format:\\@;}</style>"; response.Write(style); response.Output.Write(sw.ToString()); response.Flush(); response.End(); }
private static void WriteError(string error, HttpResponse response) { response.Clear(); response.Status = "Internal Server Error"; response.StatusCode = 500; response.Output.WriteLine(error); }
public static HttpContext FakeHttpContext() { using (var stringWriter = new StringWriter()) { var httpRequest = new HttpRequest("", "http://abc", ""); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer( "id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] {typeof(HttpSessionStateContainer)}, null) .Invoke(new object[] {sessionContainer}); return httpContext; } }
/// <summary> Serialize the return object, according to the protocol requested </summary> /// <param name="ReturnValue"> Return object to serialize </param> /// <param name="Response"> HTTP Response to write result to </param> /// <param name="Protocol"> Requested protocol type </param> /// <param name="CallbackJsonP"> Callback function for JSON-P </param> protected void Serialize(object ReturnValue, HttpResponse Response, Microservice_Endpoint_Protocol_Enum Protocol, string CallbackJsonP) { if (ReturnValue == null) return; switch (Protocol) { case Microservice_Endpoint_Protocol_Enum.JSON: JSON.Serialize(ReturnValue, Response.Output, Options.ISO8601ExcludeNulls); break; case Microservice_Endpoint_Protocol_Enum.PROTOBUF: Serializer.Serialize(Response.OutputStream, ReturnValue); break; case Microservice_Endpoint_Protocol_Enum.JSON_P: Response.Output.Write(CallbackJsonP + "("); JSON.Serialize(ReturnValue, Response.Output, Options.ISO8601ExcludeNullsJSONP); Response.Output.Write(");"); break; case Microservice_Endpoint_Protocol_Enum.XML: XmlSerializer x = new XmlSerializer(ReturnValue.GetType()); x.Serialize(Response.Output, ReturnValue); break; case Microservice_Endpoint_Protocol_Enum.BINARY: IFormatter binary = new BinaryFormatter(); binary.Serialize(Response.OutputStream, ReturnValue); break; } }
public void Flush(System.Web.HttpResponse resp) { byte[] data1 = output.ToArray(); if (!useGZip_ || data1.Length < 200) { resp.BinaryWrite(data1); return; } // compress MemoryStream ms = new MemoryStream(); GZipStream GZip = new GZipStream(ms, CompressionMode.Compress); GZip.Write(data1, 0, data1.Length); GZip.Close(); // get compressed bytes byte[] data2 = ms.ToArray(); ms.Close(); // if compression failed (more data) if (data2.Length >= data1.Length) { resp.BinaryWrite(data1); return; } resp.BufferOutput = true; resp.ContentType = "application/octet-stream"; resp.Write("$1"); //resp.Write(string.Format("SIZE: {0} vs {1}<br>", data1.Length, data2.Length)); resp.BinaryWrite(data2); resp.Flush(); }
private void GenDataTableToCSV(DataTable dTable, string FileName) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); StringBuilder sb = new StringBuilder(); string[] columnNames = dTable.Columns.Cast <DataColumn>().Select(column => column.ColumnName).ToArray(); sb.AppendLine(string.Join(",", columnNames)); foreach (DataRow row in dTable.Rows) { string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray(); sb.AppendLine(string.Join(",", fields)); } // the most easy way as you have type it response.Write(sb.ToString()); response.Flush(); response.End(); }
/// <summary> /// 文件下载 /// </summary> /// <param name="Response"></param> /// <param name="fileName"></param> /// <param name="fullPath"></param> private static void DownFile(System.Web.HttpResponse Response, string fileName, string fullPath) { //Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=UTF-8"); System.IO.FileStream fs = System.IO.File.OpenRead(fullPath); long fLen = fs.Length; int size = 1024 * 32; //每32K同时下载数据 byte[] readData = new byte[size]; //指定缓冲区的大小 if (size > fLen) { size = Convert.ToInt32(fLen); } long fPos = 0; bool isEnd = false; while (!isEnd) { if ((fPos + size) > fLen) { size = Convert.ToInt32(fLen - fPos); readData = new byte[size]; isEnd = true; } if (size > 0) { fs.Read(readData, 0, size);//读入一个压缩块 Response.BinaryWrite(readData); } fPos += size; } fs.Close(); //System.IO.File.Delete(fullPath); }
/// <summary> /// 导出文本 /// </summary> /// <param name="exportStr">导出的文本</param> /// <param name="fileName">导出的文件名</param> private static void RenderToDaoChu(string exportStr, string fileName) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; if ("" == exportStr) { return; } Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); oHtmlTextWriter.Write(exportStr); Response.Write(oStringWriter.ToString()); Response.End(); }
public Document WebExport( String fileName, System.Web.HttpResponse webResponse) { return(WebExport(false, fileName, GetDefaultPageSettings(), webResponse, null, null, "")); }
public void initializeAjaxController( System.Web.HttpRequest _request, System.Web.SessionState.HttpSessionState _session, System.Web.HttpResponse _response, System.Web.HttpServerUtility _server) { try { this.response = _response; this.request = _request; this.session = _session; this.server = _server; Thread.CurrentThread.CurrentCulture = new CultureInfo("nb-NO", false); www.fwInitialize("", "", request, session, response); ajax.Initialize(www); if (ajax.sProcedure == "init_ajax_web_form()") { ajax.setProcedure("init_bank()"); StringBuilder sb = new StringBuilder(); sb.Append(get_start_form("")); ajax.WriteHtml("bank_content", sb.ToString()); ajax.WriteXmlToClient(); } else if (ajax.sProcedure == "send_phone()") { string sPhone = ajax.getString("parameter_1"); if (sPhone.Trim().Length != 8) { ajax.WriteHtml("bank_content", get_start_form(sPhone)); } else { BankDatabaseService bankDatabase = new BankDatabaseService(); bool bExists = bankDatabase.bankPhoneExist(sPhone); bankDatabase.save_phone(sPhone); ajax.WriteVariable("status", "true"); ajax.WriteHtml("bank_content", phone_saved()); } ajax.WriteXmlToClient(); return; } sGlobalAjaxPrefix = ajax.getString("global_session_prefix"); string sGlobalSessionPrefix = (string)www.fwGetSessionVariable("global_session_prefix"); // A) NONE Ajax - prefix and NONE session : Just return. if (isBlank(sGlobalAjaxPrefix) && isBlank(sGlobalSessionPrefix)) { return; } // B) Ajax - prefix and NONE session - prefix. SAVE NEW. if (!isBlank(sGlobalAjaxPrefix) && isBlank(sGlobalSessionPrefix)) { www.fwSetSessionVariable("global_session_prefix", sGlobalAjaxPrefix); ajax.WriteVariable("initiating", "true"); global = (BankGlobal)www.fwGetSessionVariable(sGlobalAjaxPrefix + "_global"); if (global == null) { global = new BankGlobal(); www.fwSetSessionVariable(sGlobalAjaxPrefix + "_global", global); ajax.WriteVariable("initiating", "true"); return; } return; } // C) session - prefix. Just Go On if (!isBlank(sGlobalSessionPrefix)) { global = (BankGlobal)www.fwGetSessionVariable(sGlobalSessionPrefix + "_global"); return; } } catch (Exception) { } }
protected void gvregistros_RowCommand(object sender, GridViewCommandEventArgs e) { int num = Convert.ToInt32(e.CommandArgument); SqlConnection Conn = new SqlConnection(); Conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["GESTION.Properties.Settings.CadenadeConeccion"].ToString(); SqlCommand cmd = new SqlCommand(); SqlDataReader dr; if (e.CommandName == "PDF") { Conn.Open(); cmd.Connection = Conn; cmd.CommandText = "SELECT [ID_Cobro],[NDocumento],[TDocumento],[Agente],[FEmision],[Moneda],[ValorDocumento],[Observacion],[EstadoDocumento],[Usuario],[Operacion],[LinkArchivo] FROM [dbo].[CobranzaAgentes] where [ID_Cobro] = '" + num + "'"; dr = cmd.ExecuteReader(); dr.Read(); string pdfbuscar = dr["LinkArchivo"].ToString(); string Ndocumento = dr["NDocumento"].ToString(); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=Invoice " + Ndocumento + ".pdf;"); response.TransmitFile(Server.MapPath("" + pdfbuscar + "")); response.Flush(); response.End(); } if (e.CommandName == "Pagar") {// si presiona pagar se ejecuta este codigo string validar = Session["Modificar"].ToString(); if (validar == "SI") { Conn.Open(); cmd.Connection = Conn; cmd.CommandText = "SELECT [ID_Cobro],[NDocumento],[TDocumento],[Agente],[FEmision],[Moneda],[ValorDocumento],[Observacion],[EstadoDocumento],[Usuario],[Operacion],[LinkArchivo] FROM [dbo].[CobranzaAgentes] where [ID_Cobro] = '" + num + "'"; dr = cmd.ExecuteReader(); dr.Read(); txtdocumentopag.Text = dr["NDocumento"].ToString(); txtmonedapag.Text = dr["Moneda"].ToString(); DateTime Hoy = DateTime.Today; txtFechapag.Text = Hoy.ToString("dd-MM-yyyy"); btnpagar.Visible = true; txtmonto_factura.Text = dr["ValorDocumento"].ToString(); //aqui deberia solo asignar lo que queda pendiente float Valor = float.Parse(dr["ValorDocumento"].ToString()); Session["BuscarPagos"] = dr["NDocumento"].ToString(); BuscarPagos(); float pendiente = Valor - float.Parse(Session["Valor_Encontrado"].ToString()); txtmonto_Pagado.Text = pendiente.ToString();; //aqui se entrega el valor encontrado Conn.Close(); string script = @"window.location.href = '#modalHtml2';"; ScriptManager.RegisterStartupScript(this, typeof(Page), "invocarfuncion", script, true); if (txtmonto_Pagado.Text == "0") { btnpagar.Visible = false; } txtvalorpag.Text = ""; txtdetallepag.Text = ""; } else { registrook.Visible = false; sinpermisos.Visible = true; eliminarreg.Visible = false; Alertaok.Visible = false; Alertanook.Visible = false; noexiste.Visible = false; } } if (e.CommandName == "Anular")//si presiona anular { string validar = Session["Modificar"].ToString(); if (validar == "SI") { Conn.Open(); cmd.Connection = Conn; cmd.CommandText = "UPDATE CobranzaAgentes SET EstadoDocumento = 'Anulado' WHERE ID_Cobro = '" + num + "'"; dr = cmd.ExecuteReader(); dr.Read(); Conn.Close(); gvCobroAgente.DataBind(); registrook.Visible = true; sinpermisos.Visible = false; eliminarreg.Visible = false; Alertaok.Visible = false; Alertanook.Visible = false; noexiste.Visible = false; } else { registrook.Visible = false; sinpermisos.Visible = true; eliminarreg.Visible = false; Alertaok.Visible = false; Alertanook.Visible = false; noexiste.Visible = false; } } if (e.CommandName == "Ver") { Conn.Open(); cmd.Connection = Conn; cmd.CommandText = "SELECT [ID_Cobro],[NDocumento],[TDocumento],[Agente],[FEmision],[Moneda],[ValorDocumento],[Observacion],[EstadoDocumento],[Usuario],[Operacion],[LinkArchivo] FROM [dbo].[CobranzaAgentes] where [ID_Cobro] = '" + num + "'"; dr = cmd.ExecuteReader(); dr.Read(); string script = @"window.location.href = '#modalHtml3';"; ScriptManager.RegisterStartupScript(this, typeof(Page), "invocarfuncion", script, true); lblid.Text = dr["NDocumento"].ToString(); txtvaldet.Text = dr["ValorDocumento"].ToString(); txtnopedet.Text = dr["Operacion"].ToString(); txtobsdet.Text = dr["Observacion"].ToString(); txtfemidet.Text = dr["FEmision"].ToString(); txtmonedadet.Text = dr["Moneda"].ToString(); txtagentedet.Text = dr["Agente"].ToString(); Conn.Close(); } if (e.CommandName == "Eliminar") { Response.Write("Eliminar " + num + ""); string validar = Session["Eliminar"].ToString(); if (validar == "SI") { Conn.Open(); cmd.Connection = Conn; cmd.CommandText = "DELETE FROM CobranzaAgentes WHERE ID_Cobro ='" + num + "'"; dr = cmd.ExecuteReader(); dr.Read(); gvCobroAgente.DataBind(); Conn.Close(); eliminarreg.Visible = true; registrook.Visible = false; sinpermisos.Visible = false; Alertaok.Visible = false; Alertanook.Visible = false; noexiste.Visible = false; } else { registrook.Visible = false; sinpermisos.Visible = false; eliminarreg.Visible = false; Alertaok.Visible = false; Alertanook.Visible = false; noexiste.Visible = false; } } }
protected void ReprintInvoice(DataTable dt, DataTable dtPersonal, DataTable dtGST) { try { string outstd = ""; Amount = 0; Total = 0; CGSTAmt = 0; SGSTAmt = 0; DataTable dtNew = new DataTable(); for (int i = 0; i < dtPersonal.Rows.Count; i++) { int count = 0; count = 0; System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; string mailserver = string.Empty; string user = string.Empty; string pwd = string.Empty; string sentby = string.Empty; string Email = string.Empty; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { string Villa = dtPersonal.Rows[i]["Villa"].ToString(); string Resident = dtPersonal.Rows[i]["Name"].ToString(); string Adress = dtPersonal.Rows[i]["Address1"].ToString(); string Cty = dtPersonal.Rows[i]["Address3"].ToString(); string Accountcode = dtPersonal.Rows[i]["Accountcode"].ToString(); outstd = dtPersonal.Rows[i]["outstd"].ToString(); string strQuery = "Accountcode = '" + Accountcode + "'"; DateTime Odate = DateTime.Now; string printedOn = Odate.ToString("dd-MMM-yyyy hh:mm tt"); string date = Odate.ToString("dd-MMM-yyyy"); DataSet dsDetails = new DataSet(); SqlCommand cmd1 = new SqlCommand("Proc_GetGST", con); cmd1.CommandType = CommandType.StoredProcedure; SqlDataAdapter dap = new SqlDataAdapter(cmd1); dap.Fill(dsDetails); string Bmonth = dsDetails.Tables[0].Rows[0]["BPName"].ToString(); string BFROM = dsDetails.Tables[0].Rows[0]["BPFROM"].ToString(); string BTILL = dsDetails.Tables[0].Rows[0]["BPTILL"].ToString(); int drows = dsDetails.Tables[0].Rows.Count; DataTable dtservice = dt; invNo = dtservice.Rows[0]["InvoiceNo"].ToString(); string NARATION = dtservice.Rows[0]["Particulars"].ToString(); StringBuilder sb1 = new StringBuilder(); sb1.Append("<table width='100%' padding='-5PX' style='font-family:Verdana;'>"); sb1.Append("<tr><td align='Right' colspan='4' style='font-size:8px;'>Copy</td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:10px;'><b> " + commnty + " </b> </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> " + Address1 + " </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> " + Address2 + " </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> " + Address3 + " </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> GSTIN/UIN: " + gstin + " / Pan: " + Pan + " </td></tr>"); sb1.Append("</table>"); sb1.Append("<table width='100%' style='margin-left:15px;opacity:0.5;border:0.1px solid black'>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:10px;'>"); sb1.Append("Invoice No.:" + invNo + ""); sb1.Append("</td>"); sb1.Append("<td align='RIGHT' style='font-size:10px;'>"); sb1.Append("Date: " + date + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table>"); sb1.Append("<table width='100%' BORDERCOLOR='#c6ccce'>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("<b>" + Villa + "</b> - " + Resident + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("" + Adress + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("" + Cty + " "); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr >"); foreach (DataColumn column in dtservice.Columns) { if (column.ColumnName != "#") { if (column.ColumnName != "RTRSN") { if (column.ColumnName != "ACCOUNTCODE") { if (column.ColumnName != "TXNCODE") { if (column.ColumnName != "REF") { //if (column.ColumnName == "#") //{ // sb1.Append("<th style ='font-size:11px;font-family:Verdana;' align='center'>"); //} if (column.ColumnName == "Particulars") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;' colspan='1' align='center'>"); } else if (column.ColumnName == "HSN/SAC") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;' align='center'>"); } else if (column.ColumnName == "GST Rate%") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;'align='center'>"); } else if (column.ColumnName == "TaxableVlu") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;width:8%;' align='center'>"); } else if (column.ColumnName == "CGST Amt") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;'align='center'>"); } else if (column.ColumnName == "SGST Amt") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;'align='center'>"); } else if (column.ColumnName == "Total") { sb1.Append("<td style ='font-size:11px;font-family:Verdana;width:8%;' align='center'>"); } //else // { // sb1.Append("<th style ='font-size:11px;font-family:Verdana;' align='left'>"); // } if (column.ColumnName == "TaxableVlu") { sb1.Append("<b>Taxable Value</b>"); sb1.Append("</td>"); } else if (column.ColumnName == "CGST Amt") { sb1.Append("<b>CGST Amount</b>"); sb1.Append("</td>"); } else if (column.ColumnName == "SGST Amt") { sb1.Append("<b>SGST Amount</b>"); sb1.Append("</td>"); } else { sb1.Append("<b>" + column.ColumnName + "</b>"); sb1.Append("</td>"); } } } } } } } sb1.Append("</tr>"); string GST = ""; decimal amount = 0; foreach (DataRow row in dtservice.Rows) { count = count + 1; sb1.Append("<tr>"); foreach (DataColumn column in dtservice.Columns) { if (column.ColumnName != "#") { if (column.ColumnName != "RTRSN") { if (column.ColumnName != "ACCOUNTCODE") { if (column.ColumnName != "TXNCODE") { if (column.ColumnName != "REF") { //if (column.ToString() == "#") //{ // sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='center'>" + count + ""); //} if (column.ToString() == "Particulars") { sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='Left'>"); } else if (column.ToString() == "HSN/SAC") { sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } else if (column.ToString() == "GST Rate%") { GST = row[column].ToString(); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } else if (column.ToString() == "TaxableVlu") { Amount = Amount + Convert.ToDecimal(row[column]); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } else if (column.ToString() == "CGST Amt") { CGSTAmt = CGSTAmt + Convert.ToDecimal(row[column]); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } else if (column.ToString() == "SGST Amt") { SGSTAmt = SGSTAmt + Convert.ToDecimal(row[column]); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } else if (column.ToString() == "Total") { Total = Total + Convert.ToDecimal(row[column]); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } //else //{ // sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='left'>"); //} if (column.ToString() != "#") { sb1.Append(row[column]); } sb1.Append("</td>"); } } } } } } sb1.Append("</tr>"); } decimal CGST = Convert.ToDecimal(GST) / 2; count = count + 1; sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='3' style='font-size:8px;'>Total"); sb1.Append("</td>"); sb1.Append("<td align='Right' style='font-size:8px;'>" + Amount + ""); sb1.Append("</td>"); sb1.Append("<td align='Right' style='font-size:8px;'>" + CGSTAmt + ""); sb1.Append("</td>"); sb1.Append("<td align='Right' style='font-size:8px;'>" + SGSTAmt + ""); sb1.Append("</td>"); sb1.Append("<td align='Right' style='font-size:8px;'>" + Total + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' style='font-size:8px;' colspan='6'>Amount chargeable (in words)"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>E&O.E."); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' style='font-size:8px;' colspan='7'>Rupees " + ConvertToWords(Convert.ToString(Total)) + ""); Amount = amount; sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table>"); sb1.Append("<table width='100%' BORDERCOLOR='#c6ccce'>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='6' style='font-size:8px;'>Invoice Printed on " + DateTime.Now.ToString("dd-MMM-yyyy HH:mm") + " Hrs."); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table>"); sb1.Append("<table border = '1' width='50%' BORDERCOLOR='#c6ccce'"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='2' style='font-size:8px;'><b>Company’s bank details</b>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Bank name"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + BankName + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Branch"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + BranchName + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Account no"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + AccountNo + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>IFSC Code"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + IFSCCode + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table width='100%' BORDERCOLOR='#c6ccce' >"); sb1.Append("<tr>"); sb1.Append("<td align='right' colspan='4' style='font-size:8px;'>" + commnty + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<br/>"); sb1.Append("<tr>"); sb1.Append("<td align='right' colspan='4' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<br/>"); sb1.Append("<tr>"); sb1.Append("<td align='right' colspan='4' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr>"); sb1.Append("<td align='Center' colspan='4' style='font-size:10px;'>" + Jurisdiction + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='Center' colspan='4' style='font-size:8px;'>This is a computer generated invoice"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); StringReader sr2 = new StringReader(sb1.ToString()); string FileName1 = "Copy - " + invNo + "_" + Villa + "_" + Resident + "_" + NARATION + ".pdf"; //Document pdfDoc1 = new Document(PageSize.A4, 60f, 30f, 10f, 5f); Document pdfDoc2 = new Document(PageSize.A4, 60f, 30f, 10f, 5f); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName1 + ""); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); //HTMLWorker htmlparser1 = new HTMLWorker(pdfDoc1); HTMLWorker htmlparser2 = new HTMLWorker(pdfDoc2); using (MemoryStream memoryStream1 = new MemoryStream()) { string replace = FileName1.Replace(@"/", "_"); //PdfWriter writer2 = PdfWriter.GetInstance(pdfDoc2, new FileStream(@"F:\Dhinesh\Files" + @"\" + replace, FileMode.Create)); PdfWriter writer2 = PdfWriter.GetInstance(pdfDoc2, Response.OutputStream); //PdfWriter writer1 = PdfWriter.GetInstance(pdfDoc1, memoryStream1); //pdfDoc1.Open(); //writer1.PageEvent = new Footer(); //htmlparser1.Parse(sr1); //pdfDoc1.Close(); pdfDoc2.Open(); //writer2.PageEvent = new Footer(); htmlparser2.Parse(sr2); pdfDoc2.Close(); HttpContext.Current.Response.Write(pdfDoc2); HttpContext.Current.Response.Flush(); byte[] bytes1 = memoryStream1.ToArray(); memoryStream1.Close(); File = FileName1; //myMail.Attachments.Add(new Attachment(new MemoryStream(bytes1), FileName1)); } UpdateTxn(FileName1); } //End //mySmtpClient.Send(myMail); //} } dt.Dispose(); dtPersonal.Dispose(); } ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('Invoice(s) generated successfully');", true); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alert", "alert('Something went wrong." + ex.Message + "'');", true); } }
/// <summary> /// Http context handler. /// </summary> /// <param name="context">The http context.</param> public override void HttpContext(HttpContext context) { System.Web.HttpRequest request = null; System.Web.HttpResponse response = null; bool isServerError = false; bool keepAlive = true; bool isError = true; try { request = context.Request; response = context.Response; // If headers exist. if (request.Headers != null) { // Get the execution member. if (!String.IsNullOrEmpty(request.Headers["Member"])) { // Get the execution member. // Set the calling member. string executionMember = request.Headers["Member"].Trim(); response.AddHeader("Member", executionMember); response.AddHeader("ActionName", request.Headers["ActionName"]); // Create the chat state. Chat.ChatHttptState chatState = new Chat.ChatHttptState() { HttpContext = context, Member = new Net.Http.HttpContextMember(context), ExecutionMember = executionMember, ErrorCode = new Exceptions.ErrorCodeException("OK", 200) }; try { // Validate the current user token. bool isTokenValid = ValidateToken(chatState); } catch (Exceptions.ErrorCodeException exc) { // Get the error code. chatState.ErrorCode = exc; } catch (Exception ex) { // Internal error. chatState.ErrorCode = new Exceptions.ErrorCodeException(ex.Message, 500); } // Send a message back to the client indicating that // the message was recivied and was sent. CreateResponse(response, true, chatState.ErrorCode.ErrorCode, statusDescription: chatState.ErrorCode.Message); isError = false; } } else { // No headers have been found. keepAlive = false; throw new Exception("No headers have been found."); } // If error has occured. if (isError) { // Send an error response. response.StatusCode = 400; response.StatusDescription = "Bad Request"; response.AddHeader("Content-Length", (0).ToString()); response.Flush(); } } catch (Exception) { isServerError = true; } // If a server error has occured. if (isServerError) { // Make sure the response exists. if (response != null) { try { // Send an error response. response.StatusCode = 500; response.StatusDescription = "Internal server error"; response.AddHeader("Content-Length", (0).ToString()); response.Flush(); } catch { keepAlive = false; } } } // If do not keep alive. if (!keepAlive) { // Close the connection. if (response != null) { try { // Close the connection. response.Close(); } catch { } } } }
protected void Page_Load(object sender, EventArgs e) { string projectID = (Page.RouteData.Values["project_id"] as string); List <string> repsIdsToCreate = (Page.RouteData.Values["reports"] as string).Split(',').ToList(); List <Rep> repsToCreate = new List <Rep>(); foreach (string repID in repsIdsToCreate) { repsToCreate.Add(new RepBLL().GetRepByRepID(Convert.ToInt32(repID))); } bool isFullHeader = Convert.ToBoolean(Page.RouteData.Values["headeroneachreport"] as string);// cbHeaderOnEachReport.Checked; Eisk.BusinessEntities.Project project = new ProjectBLL().GetProjectByProjectID(Convert.ToInt32(projectID)); Eisk.BusinessEntities.User user = new UserBLL().GetUserByUserName((HttpContext.Current.User.Identity).Name); Eisk.BusinessEntities.UserInfo userInfo = user.UserInfoes.First(instance => instance.UserID == user.UserID); DateTime time = DateTime.Now; string name = Reports.Translate(project.ProjectInfoes.First().ProjectName); string path = System.Web.HttpContext.Current.Server.MapPath(@System.Configuration.ConfigurationManager.AppSettings["ProjectsRoot"]) + projectID.ToString(); // check folder exists if (!Directory.Exists(path)) { Directory.CreateDirectory(path); System.IO.File.WriteAllText(path + "/" + name + ".xlsx", ""); } FileInfo newFile = new FileInfo(path + @"\" + name + ".xlsx"); File.Delete(path + @"\" + name + ".xlsx"); using (ExcelPackage pck = new ExcelPackage(newFile)) { ProjectInfo projectInfo = new ProjectInfoBLL().GetProjectInfoesByProjectID(Convert.ToInt32(projectID)).First(); List <Project_Organisms> project_Organisms = new Project_OrganismsBLL().GetProject_OrganismsByProjectID(Convert.ToInt32(projectID)); int totalPages = 0; int currentPageNumber = 0; int maxLines = Convert.ToInt32(@System.Configuration.ConfigurationManager.AppSettings["reportsMaxLines"]); List <TreeDetail> treeDetails = new List <TreeDetail>(); List <TreeDetail> treeComentaries = new List <TreeDetail>(); List <TreesSummary> actionProposedID0Items = new List <TreesSummary>(); List <TreesSummary> actionProposedID1Items = new List <TreesSummary>(); List <TreesSummary> actionProposedID2Items = new List <TreesSummary>(); List <TreesSummary> actionProposedID3Items = new List <TreesSummary>(); List <TreesSummary> actionProposedID4Items = new List <TreesSummary>(); int treeDetailsCount = 0; int actionProposedID0ItemsCount = 0; int actionProposedID1ItemsCount = 0; int actionProposedID2ItemsCount = 0; int actionProposedID3ItemsCount = 0; int actionProposedID4ItemsCount = 0; List <Index> idexes = new List <Index>(); if (repsToCreate.Select(instance => instance.RepID).Contains(1)) { idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 1).Select(instance => instance.RepName).First(), 1, totalPages + 1, totalPages + 1 )); totalPages += 1; } if (repsToCreate.Select(instance => instance.RepID).Contains(2)) { treeDetails = new TreeDetailBLL().GetTreeDetailsByProjectID(Convert.ToInt32(projectID)); treeDetailsCount += Reports.GetPageCountOrDefault(maxLines, treeDetails.Count); idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 2).Select(instance => instance.RepName).First(), 2, totalPages + 1, totalPages + treeDetailsCount )); totalPages += treeDetailsCount; } if (repsToCreate.Select(instance => instance.RepID).Contains(3)) { actionProposedID0Items = new TreesSummaryBLL().GetItems(project_Organisms, 0, true); actionProposedID0ItemsCount = Reports.GetPageCountOrDefault(maxLines, actionProposedID0Items.Count); ; idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 3).Select(instance => instance.RepName).First(), 3, totalPages + 1, totalPages + actionProposedID0ItemsCount )); totalPages += actionProposedID0ItemsCount; } if (repsToCreate.Select(instance => instance.RepID).Contains(4)) { actionProposedID1Items = new TreesSummaryBLL().GetItems(project_Organisms, 1, true); actionProposedID1ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID1Items.Count); idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 4).Select(instance => instance.RepName).First(), 4, totalPages + 1, totalPages + actionProposedID1ItemsCount )); totalPages += actionProposedID1ItemsCount; } if (repsToCreate.Select(instance => instance.RepID).Contains(5)) { actionProposedID2Items = new TreesSummaryBLL().GetItems(project_Organisms, 2, true); actionProposedID2ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID2Items.Count); idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 5).Select(instance => instance.RepName).First(), 5, totalPages + 1, totalPages + actionProposedID2ItemsCount )); totalPages += actionProposedID2ItemsCount; } if (repsToCreate.Select(instance => instance.RepID).Contains(6)) { actionProposedID3Items = new TreesSummaryBLL().GetItems(project_Organisms, 3, true); actionProposedID3ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID3Items.Count); idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 6).Select(instance => instance.RepName).First(), 6, totalPages + 1, totalPages + actionProposedID3ItemsCount )); totalPages += actionProposedID3ItemsCount; } if (repsToCreate.Select(instance => instance.RepID).Contains(7)) { actionProposedID4Items = new TreesSummaryBLL().GetItems(project_Organisms, 4, true); actionProposedID4ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID4Items.Count); idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 7).Select(instance => instance.RepName).First(), 7, totalPages + 1, totalPages + actionProposedID4ItemsCount )); totalPages += actionProposedID4ItemsCount; } if (repsToCreate.Select(instance => instance.RepID).Contains(8)) { idexes.Add( new Index( repsToCreate.Where(instance => instance.RepID == 8).Select(instance => instance.RepName).First(), 1, totalPages + 1, totalPages + 1 )); totalPages += 1; } if (repsToCreate.Select(instance => instance.RepID).Contains(2)) // Se repite el ID de inventario de arboles para anejar comentarios muy largos { treeComentaries = treeDetails.AsQueryable().DynamicOrderBy("Number").Where(instance => instance.Commentary.Trim().Length > 100).ToList(); int totalTreeDetailsLines = 0; int pageCount = 0; foreach (var treeDetail in treeComentaries) { int lines = (int)Math.Ceiling((double)treeDetail.Commentary.Length / 200D); if (totalTreeDetailsLines + lines > maxLines * pageCount) { pageCount++; } totalTreeDetailsLines += lines; } if (treeComentaries.Count > 0) { idexes.Add( new Index( "Comentarios (Continuación)", 0, totalPages + 1, totalPages + pageCount )); } //int pageCount = (int)Math.Ceiling((double)totalTreeDetailsLines / (double)maxLines); totalPages += pageCount; } bool hasIndex = Convert.ToBoolean(Page.RouteData.Values["createindex"] as string); if (hasIndex)//cbCreateIndex.Checked) { Reports.Index(isFullHeader, currentPageNumber, totalPages, "Tabla de Contenido", project, userInfo, idexes, time, pck); } foreach (Int32 reportID in repsToCreate.Select(instance => instance.RepID)) { switch (reportID) { case 1: { Reports.ProjectInfo(isFullHeader, hasIndex, currentPageNumber, totalPages, project, userInfo, time, pck); currentPageNumber += 1; } break; case 2: { Reports.TreeInventory(isFullHeader, hasIndex, currentPageNumber, totalPages, project, userInfo, treeDetails.AsQueryable().DynamicOrderBy("Number").ToList(), time, pck, maxLines); currentPageNumber += treeDetailsCount; } break; case 3: { // actionProposedID = 0; ALL Reports.TreesSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, project, userInfo, actionProposedID0Items, time, pck, maxLines); currentPageNumber += actionProposedID0ItemsCount; } break; case 4: { // actionProposedID = 1; Corte y Remoción Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Corte y Remoción", project, userInfo, actionProposedID1Items, time, pck, maxLines); currentPageNumber += actionProposedID1ItemsCount; } break; case 5: { // actionProposedID = 2; Protección Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Protección", project, userInfo, actionProposedID2Items, time, pck, maxLines); currentPageNumber += actionProposedID2ItemsCount; } break; case 6: { // actionProposedID = 3; Poda Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Poda", project, userInfo, actionProposedID3Items, time, pck, maxLines); currentPageNumber += actionProposedID3ItemsCount; } break; case 7: { // actionProposedID = 4; Transplante Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Transplante", project, userInfo, actionProposedID4Items, time, pck, maxLines); currentPageNumber += actionProposedID4ItemsCount; } break; case 8: { using (ExcelPackage pck2 = new OfficeOpenXml.ExcelPackage()) { ExcelWorksheet wsTemplate = null; pck2.Load(File.OpenRead(System.Web.HttpContext.Current.Server.MapPath(@"~\App_Resources\Excel\Totales.xlsx"))); wsTemplate = pck2.Workbook.Worksheets.First(); Reports.ProjectResults(isFullHeader, hasIndex, currentPageNumber, totalPages, project_Organisms, project, userInfo, time, pck, wsTemplate); currentPageNumber += 1; } } break; default: break; } } if (treeComentaries.Count > 0 && treeDetailsCount > 0) { Reports.Comentaries(isFullHeader, hasIndex, currentPageNumber, totalPages, "Comentarios (Continuación)", project, userInfo, treeComentaries, time, pck, maxLines); } pck.Save(); pck.Dispose(); } System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/ms-excel"; response.AddHeader("Content-Disposition", "attachment; filename=" + name + ".xlsx"); response.WriteFile(path + @"/" + name + ".xlsx"); response.End(); }
private bool datos_promocion(string _Articulo, string _Tarifa, string _Cliente) { Respuesta_1_lbl.Text = "Procesando..."; Respuesta_1_lbl.Visible = true; Respuesta_2_lbl.Visible = true; string sql = "select * from V_CLIENTES_ARTICULOS_PROMO_ where ARTICULO=175 and TARIFA=10"; if (_Articulo.Length == 0 && _Tarifa.Length == 0 && _Cliente.Length == 0) { sql = "select * from V_CLIENTES_ARTICULOS_PROMO_ "; } else { sql = "select * from V_CLIENTES_ARTICULOS_PROMO_ where "; } if (_Articulo.Length > 0 && _Tarifa.Length == 0 && _Cliente.Length == 0) { sql += @"ARTICULO='" + _Articulo + @"'"; } else if (_Articulo.Length > 0 && (_Tarifa.Length > 0 || _Cliente.Length == 0)) { sql += @"ARTICULO='" + _Articulo + @"' AND "; } if (_Tarifa.Length > 0 && _Cliente.Length == 0) { sql += " TARIFA=" + _Tarifa; } else if (_Tarifa.Length > 0 && _Cliente.Length > 0) { sql += " TARIFA=" + _Tarifa + " AND "; } if (_Cliente.Length > 0) { sql += " CLIENTE=" + _Cliente; } // datos = Session["datos"] as DataTable; using (ExcelPackage pck = new ExcelPackage()) { ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Promociones"); ws.Cells["A1"].LoadFromDataTable(con.Sql_Datatable(sql), true, OfficeOpenXml.Table.TableStyles.Medium14); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; // make sure it is sent as a XLSX file Response.ContentType = "application/vnd.ms-excel"; // make sure it is downloaded rather than viewed in the browser window Response.AddHeader("Content-disposition", "attachment; filename=Tarifas.xlsx"); byte[] a = pck.GetAsByteArray(); Response.OutputStream.Write(a, 0, a.Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); } Respuesta_1_lbl.Text = "Excel exportado correctamente"; Respuesta_2_lbl.Visible = false; return(true); }
private void ExportContent(string exportType) { string pageSource = PageSourceHiddenField.Value; pageSource = "<html>" + pageSource.Replace("#g#", ">").Replace("#l#", "<") + "</html>"; pageSource = pageSource.Replace("<div class=" + "\"exportButton\"" + ">", "<div class=" + "\"exportButton\"" + "style=" + "\"display: none\"" + ">"); // To make the relative image paths work, base URL must be included in head section pageSource = pageSource.Replace("</head>", string.Format("<base href='{0}'></base></head>", BaseURL)); // Check for license and apply if exists string licenseFile = Server.MapPath("~/App_Data/Aspose.Words.lic"); if (File.Exists(licenseFile)) { License license = new License(); license.SetLicense(licenseFile); } MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(pageSource)); Document doc = new Document(stream); string fileName = GetOutputFileName("." + exportType); if (doc.PageCount > 1) { Directory.CreateDirectory(Server.MapPath("~/App_Data/" + "Zip")); if (exportType.Equals("Jpeg") || exportType.Equals("Png")) { fileName = GetOutputFileName(exportType).Replace(exportType, ""); // Convert the html , get page count and save PNG's in Images folder for (int i = 0; i < doc.PageCount; i++) { if (exportType.Equals("Jpeg")) { ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg); saveOptions.PageSet = new PageSet(i); doc.Save(Server.MapPath("~/App_Data/Zip/") + fileName + "/" + (i + 1).ToString() + "." + exportType, saveOptions); } else { ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Png); saveOptions.PageSet = new PageSet(i); doc.Save(Server.MapPath("~/App_Data/Zip/") + fileName + "/" + (i + 1).ToString() + "." + exportType, saveOptions); } } string filepath = Server.MapPath("~/App_Data/Zip/" + fileName + "/"); string downloadDirectory = Server.MapPath("~/App_Data/"); ZipFile.CreateFromDirectory(filepath, downloadDirectory + fileName + ".zip", System.IO.Compression.CompressionLevel.Optimal, false); Directory.Delete(Server.MapPath("~/App_Data/Zip/" + fileName), true); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "App_Data/" + exportType; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip;"); response.TransmitFile("~/App_Data/" + fileName + ".zip"); //File.Delete(Server.MapPath("~/App_Data/" + fileName + ".zip")); response.End(); return; } } doc.Save(Response, fileName, ContentDisposition.Attachment, null); Response.End(); }
protected void exportToExcel() { string file = ""; try { DateTime dtFrom = DateTime.Today, dtTo = DateTime.Today; if (Convert.ToString(txtFromDate.Text) != "" && Convert.ToString(txtFromDate.Text) != null) { dtFrom = DateTime.Parse(txtFromDate.Text); } if (Convert.ToString(txtToDate.Text) != "" && Convert.ToString(txtToDate.Text) != null) { dtTo = DateTime.Parse(txtToDate.Text); } if (dtTo < dtFrom) { divError.InnerHtml = "<b> <font color=\"red\"> Please select proper To and From Dates. </font> </b>"; } System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; file = ConfigurationManager.ConnectionStrings["FilePath"].ConnectionString; // "C:\\Report.xls" // +DateTime.Now.ToString().Replace("/", "_").Replace(":", "_") + ".xls"; Workbook workbook = new Workbook(); Worksheet worksheet = new Worksheet("First Sheet"); string[] colNames = { "Id", "Sent Date", "Company Website", "Company Name", "Client EmailId", "Client Name", "Client Phone" }; // "Company Phone" for (int i = 0; i < colNames.Length; i++) { worksheet.Cells[0, i] = new Cell(colNames[i]); worksheet.Cells.ColumnWidth[0, (ushort)i] = 5000; } DataSet ds = new DataSet("dsEmailsInfo"); using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString)) { SqlCommand cmd = new SqlCommand("sp_getEmailsInfo", con); if (dtFrom == DateTime.Today && dtTo == DateTime.Today) //From and To dates are null for getting all records { cmd.Parameters.AddWithValue("@startDate", DBNull.Value); cmd.Parameters.AddWithValue("@endDate", DBNull.Value); } else if (dtFrom == DateTime.Today && dtTo != DateTime.Today) //From and To dates are null for getting all records { cmd.Parameters.AddWithValue("@startDate", DBNull.Value); cmd.Parameters.AddWithValue("@endDate", dtTo); } else { cmd.Parameters.AddWithValue("@startDate", dtFrom); cmd.Parameters.AddWithValue("@endDate", dtTo); } cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; da.Fill(ds, "EmailsInfo"); DataTable dt = ds.Tables[0]; int intRowNo = 1; int intSrNo = 1; foreach (DataRow row in dt.Rows) { intRowNo++; int i = 0; foreach (DataColumn col in dt.Columns) { if (i == 0) { worksheet.Cells[intRowNo, i++] = new Cell(Convert.ToString(intSrNo++)); worksheet.Cells.ColumnWidth[(ushort)intRowNo, (ushort)i] = 1000; } else { worksheet.Cells[intRowNo, i++] = new Cell(Convert.ToString(row[col])); worksheet.Cells.ColumnWidth[(ushort)intRowNo, (ushort)i] = 6000; } } } } workbook.Worksheets.Add(worksheet); //----------------------------------------- worksheet = new Worksheet("Second Sheet"); for (int i = 0; i < 550; i++) { worksheet.Cells[i, 0] = new Cell(i); } workbook.Worksheets.Add(worksheet); //----------------------------------------------------------- workbook.Save(file); string name = file.Substring((file.LastIndexOf("\\") + 1)); string fileName = "Report" + DateTime.Now.ToString().Replace("/", "_").Replace(":", "_") + ".xls"; string type = "application/vnd.ms-excel"; if (true) { Response.AppendHeader("content-disposition", "attachment; filename=" + fileName); } if (type != "") { Response.ContentType = type; Response.WriteFile(file); Response.End(); } } catch (Exception ex) { btnScanEmails.Visible = false; btnExportToExcel.Visible = false; divError.InnerText = Convert.ToString(ex); } }
private void DownLoadPaperPDF() { string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid={1}&isPdf=1", Request.Url.Host, RequestEPID); BLL.Loger.Log4Net.Info("试卷导出PDF,访问URL:" + url); byte[] downloadBytes = new byte[] { }; string downloadName = "文字版试卷.pdf"; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "Get"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.KeepAlive = true; Uri uri = new Uri(url); CookieContainer cookies = new CookieContainer(); string name = BLL.Util.SysLoginCookieName; cookies.Add(uri, new Cookie(name, HttpContext.Current.Request.Cookies[name].Value)); request.CookieContainer = cookies; var s = request.GetResponse(); var r = new StreamReader(s.GetResponseStream(), Encoding.UTF8); var htmlText = r.ReadToEnd(); BLL.Loger.Log4Net.Info("试卷导出PDF—生成前文本内容:" + htmlText); htmlText = htmlText.Replace("<input name=", "<span name="); int iV = htmlText.IndexOf("<div class=\"taskT\">"); htmlText = htmlText.Replace("<div class=\"taskT\">", ""); if (iV > 0) { int iVLast = htmlText.IndexOf("div>", iV); if (iVLast > 0) { htmlText = htmlText.Substring(0, iV + 1) + htmlText.Substring(iVLast + 4); } } int iName = htmlText.IndexOf("iname=\"1\""); if (iName > 0) { int iNameE = htmlText.IndexOf("</b>", iName); if (iNameE > 0) { downloadName = HttpUtility.UrlEncode(htmlText.Substring(iName + 9 + 1, iNameE - iName - 10).Trim(), Encoding.UTF8).Replace("+", "%20") + ".pdf"; } } BLL.Loger.Log4Net.Info("试卷导出PDF—生成文件名:" + downloadName); PdfConverter pdfConverter = GetPdfConvert(); downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlText); } catch (Exception ex) { downloadBytes = new byte[] { }; BLL.Loger.Log4Net.Error("在页面ExamPaperPDF.aspx 报错:" + ex.Message, ex); } try { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); } catch (Exception ex) { BLL.Loger.Log4Net.Error("导出试卷pdf", ex); } }
public void DiningInvoice() { int count = 0; DataTable dtNew = new DataTable(); DataTable dtPersonal = new DataTable(); DataTable dt = new DataTable(); try { for (int i = 0; i < dtPersonal.Rows.Count; i++) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; string mailserver = string.Empty; string user = string.Empty; string pwd = string.Empty; string sentby = string.Empty; string Email = string.Empty; SqlCommand cmd = new SqlCommand("Proc_GetEmailCredentials", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet dsCredential = new DataSet(); da.Fill(dsCredential); // Write an informational entry to the event log. if (dsCredential != null && dsCredential.Tables.Count > 0) { foreach (DataRow row in dsCredential.Tables[0].Rows) { mailserver = row["mailserver"].ToString(); user = row["username"].ToString(); pwd = row["password"].ToString(); sentby = row["sentbyuser"].ToString(); Email = row["Email"].ToString(); } } SmtpClient mySmtpClient = new SmtpClient(mailserver, 587); MailAddress From = new MailAddress(user, "*****@*****.**"); MailMessage myMail = new System.Net.Mail.MailMessage(); myMail.From = From; myMail.To.Add(Email); myMail.CC.Add("[email protected] "); mySmtpClient.UseDefaultCredentials = false; System.Net.NetworkCredential basicauth = new System.Net.NetworkCredential(user, pwd); mySmtpClient.Credentials = basicauth; mySmtpClient.EnableSsl = false; mySmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //mySmtpClient.Timeout = 200000; myMail.SubjectEncoding = System.Text.Encoding.UTF8; myMail.BodyEncoding = System.Text.Encoding.UTF8; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { string Villa = dtPersonal.Rows[i]["Villa"].ToString(); string Resident = dtPersonal.Rows[i]["Name"].ToString(); string Adress = dtPersonal.Rows[i]["Address1"].ToString(); string Cty = dtPersonal.Rows[i]["Address3"].ToString(); string Accountcode = dtPersonal.Rows[i]["Accountcode"].ToString(); string strQuery = "Accountcode = '" + Accountcode + "'"; DateTime Odate = DateTime.Now; string printedOn = Odate.ToString("dd-MMM-yyyy hh:mm tt"); string date = Odate.ToString("dd-MMM-yyyy"); //DINING INVOICE DataSet dsINVOICE = new DataSet(); SqlCommand cmd2 = new SqlCommand("Proc_GetINVOICEDETAILS", con); cmd2.CommandType = CommandType.StoredProcedure; cmd2.Parameters.AddWithValue("@TXNCODE", "DI"); SqlDataAdapter daI = new SqlDataAdapter(cmd2); daI.Fill(dsINVOICE, "temp"); string INVOICENO = dsINVOICE.Tables[0].Rows[0]["PREFIX"].ToString() + "/" + dsINVOICE.Tables[0].Rows[0]["YEAR"].ToString() + "/" + dsINVOICE.Tables[0].Rows[0]["CODE"].ToString(); string NARATION = dsINVOICE.Tables[0].Rows[0]["STDTEXT"].ToString(); DataTable dtservice = null; string where = "txncode in ('DI','AC') "; string whr = strQuery + " and " + where; DataSet dsDetails = new DataSet(); SqlCommand cmd1 = new SqlCommand("Proc_GetGST", con); cmd1.CommandType = CommandType.StoredProcedure; cmd1.Parameters.AddWithValue("@where", whr); SqlDataAdapter dap = new SqlDataAdapter(cmd1); dap.Fill(dsDetails, "temp"); decimal Calc = Convert.ToDecimal(dsDetails.Tables[0].Rows[0]["GST"].ToString()) + Convert.ToDecimal(dsDetails.Tables[0].Rows[1]["GST"].ToString()); decimal sp = Calc / 2; DataRow[] drfilService = dt.Select(where); if (drfilService.Any()) { dtservice = drfilService.CopyToDataTable(); // dtservice.DefaultView.Sort = "Date ASC"; StringBuilder sb1 = new StringBuilder(); sb1.Append("<table width='100%' padding='-5PX' style='font-family:Verdana;margin-left:15px;'>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:10px;'><b> " + commnty + " </b> </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> " + Address1 + " </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> " + Address2 + " </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> " + Address3 + " </td></tr>"); sb1.Append("<tr><td align='center' colspan='4' style='font-size:9px;'> GSTIN/UIN:33AAFCC6261P1ZC / Pan: AAFCC6261P </td></tr>"); //sb1.Append("<tr><td align='center' colspan='4' style='font-size:10px;'> GSTIN/UIN:" + gstin + " / Pan: " + Pan + " </td></tr>"); sb1.Append("</table>"); sb1.Append("<br/>"); sb1.Append("<table border = '1' width='100%' style='margin-left:15px;opacity:0.5;border:0.1px solid black'>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:10px;'>"); sb1.Append("<b>Tax Invoice</b> "); sb1.Append("</td>"); sb1.Append("<td align='RIGHT' style='font-size:10px;'>"); sb1.Append("Invoice No:" + INVOICENO + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:10px;'>"); sb1.Append("" + NARATION + ""); sb1.Append("</td>"); sb1.Append("<td align='RIGHT' style='font-size:10px;'>"); sb1.Append("Invoice Date: " + date + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table>"); sb1.Append("<br/>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("<b>To:" + Villa + "</b> "); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("" + Resident + ":"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("<b></b> "); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("" + Adress + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr >"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("<b></b> "); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("" + Cty + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr >"); foreach (DataColumn column in dtservice.Columns) { if (column.ColumnName != "RTRSN") { if (column.ColumnName != "Accountcode") { if (column.ColumnName == "#") { sb1.Append("<th style ='font-size:11px;font-family:Verdana;' align='center'>"); } else if (column.ColumnName == "Particulars") { sb1.Append("<th style ='font-size:11px;font-family:Verdana;' align='Left'>"); } else if (column.ColumnName == "HSN/SAC") { sb1.Append("<th style ='font-size:11px;font-family:Verdana;' align='center'>"); } else if (column.ColumnName == "GST Rate%") { sb1.Append("<th style ='font-size:11px;font-family:Verdana;'align='right'>"); } else if (column.ColumnName == "Amount") { sb1.Append("<th style ='font-size:11px;font-family:Verdana;width:8%;' align='right'>"); } //else // { // sb1.Append("<th style ='font-size:11px;font-family:Verdana;' align='left'>"); // } sb1.Append(column.ColumnName); sb1.Append("</th>"); } } } sb1.Append("</tr>"); string GST = ""; decimal amount = 0; foreach (DataRow row in dtservice.Rows) { count = count + 1; sb1.Append("<tr>"); foreach (DataColumn column in dtservice.Columns) { if (column.ToString() != "RTRSN") { if (column.ToString() != "Accountcode") { if (column.ToString() == "#") { sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='center'>" + count + ""); } else if (column.ToString() == "Particulars") { sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='Left'>"); } else if (column.ToString() == "HSN/SAC") { sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='center'>"); } else if (column.ToString() == "GST Rate%") { GST = row[column].ToString(); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } else if (column.ToString() == "Amount") { amount = amount + Convert.ToDecimal(row[column]); sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='right'>"); } //else //{ // sb1.Append("<td style = 'font-size:8px;font-family:Verdana;' align='left'>"); //} if (column.ToString() != "#") { sb1.Append(row[column]); } sb1.Append("</td>"); } } } sb1.Append("</tr>"); } decimal CGST = Convert.ToDecimal(GST) / 2; count = count + 1; sb1.Append("<tr>"); sb1.Append("<td align='center' style='font-size:8px;'>" + count + ""); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>Output CGST"); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + CGST + ""); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + sp + ""); sb1.Append("</td>"); sb1.Append("</tr>"); count = count + 1; sb1.Append("<tr>"); sb1.Append("<td align='center' style='font-size:8px;'>" + count + ""); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>Output SGST"); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + CGST + ""); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + sp + ""); sb1.Append("</td>"); sb1.Append("</tr>"); amount = amount + Calc; sb1.Append("<tr>"); sb1.Append("<td align='center' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>Total"); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='Left' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + amount + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' style='font-size:8px;' colspan='4'>Amount chargeable (in words)"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>E&O.E."); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' style='font-size:8px;' colspan='5'> Rupees Two Thousand Nine Hundred Sixty One and Twenty Nine Paise only"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr>"); sb1.Append("<td colspan='2' style='font-size:8px;'>HSN/SAC"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;' align='right'>GST Rate %"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;' align='right'>Amount"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td colspan='2' style='font-size:8px;'> 999322"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td colspan='2'style='font-size:8px;'> Taxable amount"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td colspan='2' style='font-size:8px;'> CGST"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + CGST + ""); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + sp + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td colspan='2' style='font-size:8px;'> SGST"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + CGST + ""); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + sp + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td colspan='2' style='font-size:8px;'> Tax amount"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>" + Calc + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td colspan='3' style='font-size:8px;'> Rupees One Hundred forty One and Zero Two Paise Only"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("<td align='right' style='font-size:8px;'>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='4' style='font-size:8px;'>Remarks :"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='4' style='font-size:8px;'>" + NARATION + " for the month of 26.11.17 to 25.12.17"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Company’s bank details"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Bank name"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + BankName + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Branch"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + BranchName + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>Account no"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + AccountNo + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='left' colspan='1' style='font-size:8px;'>IFSC Code"); sb1.Append("</td>"); sb1.Append("<td style='font-size:8px;'>" + IFSCCode + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table border = '1' width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr>"); sb1.Append("<td align='right' colspan='4' style='font-size:8px;'>For " + commnty + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='right' colspan='4' style='font-size:8px;'>Authorized signatory"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); sb1.Append("<table width='100%' BORDERCOLOR='#c6ccce' style='margin-left:15px;'>"); sb1.Append("<tr>"); sb1.Append("<td align='Center' colspan='4' style='font-size:10px;'>" + Jurisdiction + ""); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("<tr>"); sb1.Append("<td align='Center' colspan='4' style='font-size:8px;'>This is a computer generated invoice"); sb1.Append("</td>"); sb1.Append("<td>"); sb1.Append("</td>"); sb1.Append("</tr>"); sb1.Append("</table><br/>"); StringReader sr1 = new StringReader(sb1.ToString()); //sb1.Length = 0; //sb1.Clear(); Document pdfDoc1 = new Document(PageSize.A4, 60f, 30f, 10f, 5f); HTMLWorker htmlparser1 = new HTMLWorker(pdfDoc1); using (MemoryStream memoryStream1 = new MemoryStream()) { PdfWriter writer1 = PdfWriter.GetInstance(pdfDoc1, memoryStream1); pdfDoc1.Open(); //writer1.PageEvent = new Footer(); htmlparser1.Parse(sr1); pdfDoc1.Close(); byte[] bytes1 = memoryStream1.ToArray(); memoryStream1.Close(); string FileName1 = "Invoice For Dining._" + Villa + "" + ".pdf"; myMail.Attachments.Add(new Attachment(new MemoryStream(bytes1), FileName1)); } myMail.IsBodyHtml = true; myMail.Subject = Resident + " - Dec17 - " + Villa + " - Statement for " + "" + " - " + commnty; myMail.Body = "Testing"; mySmtpClient.Send(myMail); } } } } dt.Dispose(); dtPersonal.Dispose(); } catch (Exception ex) { WebMsgBox.Show(ex.Message); } }
public Export() { appType = "Web"; response = System.Web.HttpContext.Current.Response; }
/// <summary> /// Copies response internals suh as status code, cookies and stuff /// </summary> /// <param name="input"></param> /// <param name="output"></param> public static void CopyResponseInternals(this System.Net.HttpWebResponse input, System.Web.HttpResponse output) { if (input != null) { output.StatusCode = (int)input.StatusCode; output.StatusDescription = input.StatusDescription; output.ContentType = input.ContentType; // copy input cookies so teh can be passed to the client foreach (System.Net.Cookie cookie in input.Cookies) { System.Web.HttpCookie c = new System.Web.HttpCookie(cookie.Name); c.Value = cookie.Value; output.Cookies.Add(c); } } }
public Document WebExport( Boolean openCloseConnection, String fileName, System.Web.HttpResponse webResponse, string waterMark = "") { return(WebExport(openCloseConnection, fileName, null, webResponse, null, null, waterMark)); }
private void DownLoadPDF() { string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid={1}&isPdf=1", Request.Url.Host, RequestEPID); #region Cookies添加 //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl); //request.Credentials = CredentialCache.DefaultCredentials; //request.Headers.Add("Cookie", Request.Headers["Cookie"]); //request.CookieContainer = new CookieContainer(); ////string strCookieFilter = ".ASPXAUTH,BitAutoLogId,BitAutoUserCode,ASP.NET_SessionId,mmploginusername"; //string strCookieFilter = "BitAutoLogId,BitAutoUserCode,ASP.NET_SessionId,mmploginusername"; //HttpCookieCollection oCookies = Context.Request.Cookies; //for (int j = 0; j < oCookies.Count; j++) //{ // HttpCookie oCookie = oCookies.Get(j); // if (strCookieFilter.IndexOf(oCookie.Name) > -1) // { // Cookie oC = new Cookie(); // // Convert between the System.Net.Cookie to a System.Web.HttpCookie... // oC.Domain = Context.Request.Url.Host; // myRequest.RequestUri.Host; // oC.Expires = oCookie.Expires; // oC.Name = oCookie.Name; // oC.Path = oCookie.Path; // oC.Secure = oCookie.Secure; // oC.Value = oCookie.Value.Replace(",", "%2C"); // request.CookieContainer.Add(oC); // } //} //var s = request.GetResponse(); //var r = new StreamReader(s.GetResponseStream(), Encoding.UTF8); //var htmlText = r.ReadToEnd(); //htmlText = htmlText.Replace("<input name=", "<span name="); //htmlText = htmlText.Replace("<div class=\"taskT\">试卷查看</div>", ""); #endregion byte[] downloadBytes = new byte[] { }; string downloadName = "网页版试卷.pdf"; try { PdfConverter pdfConverter = GetPdfConvert(); //var downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlText); //var downloadBytes = pdfConverter.GetPdfBytesFromUrl("http://ncc.sys1.bitauto.com/AjaxServers/ExamOnline/tt.htm"); downloadBytes = pdfConverter.GetPdfBytesFromUrl(url); } catch (Exception ex) { downloadBytes = new byte[] { }; BLL.Loger.Log4Net.Info("在页面ExamPaperPDF.aspx 报错:" + ex.Message); } System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); }
public void ProcessRequest(HttpContext context) { string sPath = string.Empty; string sNomFactura = oWeb.GetData("sNomFactura"); string sNumContrato = oWeb.GetData("sNumContrato"); DBConn oConn = new DBConn(); if (oConn.Open()) { cContratos oContratos = new cContratos(ref oConn); oContratos.NumContrato = sNumContrato; DataTable dtContrato = oContratos.Get(); if (dtContrato != null) { if (dtContrato.Rows.Count > 0) { cCliente oCliente = new cCliente(ref oConn); oCliente.NkeyCliente = dtContrato.Rows[0]["nkey_cliente"].ToString(); DataTable dtCliente = oCliente.Get(); if (dtCliente != null) { if (dtCliente.Rows.Count > 0) { sPath = dtCliente.Rows[0]["pathsdocscaneados"].ToString() + "\\" + dtCliente.Rows[0]["direcarchivos"].ToString(); } } dtContrato = null; } } } oConn.Close(); System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; sPath = sPath + "\\" + sNomFactura + ".pdf"; oResponse.ContentType = "application/pdf"; oResponse.AppendHeader("Content-Disposition", "attachment; filename=" + sNomFactura + ".pdf"); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = new FileStream(sPath, FileMode.Open, FileAccess.Read); do { if (oResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); oResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); oResponse.Flush(); oResponse.End(); } finally { if (download != null) { download.Close(); } } }
public override void SendResponse(System.Web.HttpResponse response) { int iErrorNumber = 0; string sFileName = ""; string sUnsafeFileName = ""; try { this.CheckConnector(); this.CheckRequest(); if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileUpload)) { ConnectorException.Throw(Errors.Unauthorized); } HttpPostedFile oFile = HttpContext.Current.Request.Files[HttpContext.Current.Request.Files.AllKeys[0]]; if (oFile != null) { sUnsafeFileName = System.IO.Path.GetFileName(oFile.FileName); sFileName = Regex.Replace(sUnsafeFileName, @"[\:\*\?\|\/]", "_", RegexOptions.None); if (sFileName != sUnsafeFileName) { iErrorNumber = Errors.UploadedInvalidNameRenamed; } if (Connector.CheckFileName(sFileName) && !Config.Current.CheckIsHiddenFile(sFileName)) { // Replace dots in the name with underscores (only one dot can be there... security issue). if (Config.Current.ForceSingleExtension) { sFileName = Regex.Replace(sFileName, @"\.(?![^.]*$)", "_", RegexOptions.None); } if (!Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && oFile.ContentLength > this.CurrentFolder.ResourceTypeInfo.MaxSize) { ConnectorException.Throw(Errors.UploadedTooBig); } string sExtension = System.IO.Path.GetExtension(oFile.FileName); sExtension = sExtension.TrimStart('.'); if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(sExtension)) { ConnectorException.Throw(Errors.InvalidExtension); } if (Config.Current.CheckIsNonHtmlExtension(sExtension) && !this.CheckNonHtmlFile(oFile)) { ConnectorException.Throw(Errors.UploadedWrongHtmlFile); } // Map the virtual path to the local server path. string sServerDir = this.CurrentFolder.ServerPath; string sFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension(sFileName); int iCounter = 0; while (true) { string sFilePath = System.IO.Path.Combine(sServerDir, sFileName); if (System.IO.File.Exists(sFilePath)) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + System.IO.Path.GetExtension(oFile.FileName); iErrorNumber = Errors.UploadedFileRenamed; } else { oFile.SaveAs(sFilePath); if (Config.Current.SecureImageUploads && ImageTools.IsImageExtension(sExtension) && !ImageTools.ValidateImage(sFilePath)) { System.IO.File.Delete(sFilePath); ConnectorException.Throw(Errors.UploadedCorrupt); } Settings.Images imagesSettings = Config.Current.Images; if (imagesSettings.MaxHeight > 0 && imagesSettings.MaxWidth > 0) { ImageTools.ResizeImage(sFilePath, sFilePath, imagesSettings.MaxWidth, imagesSettings.MaxHeight, true, imagesSettings.Quality); if (Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0) { long fileSize = new System.IO.FileInfo(sFilePath).Length; if (fileSize > this.CurrentFolder.ResourceTypeInfo.MaxSize) { System.IO.File.Delete(sFilePath); ConnectorException.Throw(Errors.UploadedTooBig); } } } break; } } } else { ConnectorException.Throw(Errors.InvalidName); } } else { ConnectorException.Throw(Errors.UploadedCorrupt); } } catch (ConnectorException connectorException) { iErrorNumber = connectorException.Number; } catch (System.Security.SecurityException) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch (System.UnauthorizedAccessException) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch { #if DEBUG throw; #else iErrorNumber = Errors.Unknown; #endif } #if DEBUG if (iErrorNumber == Errors.None || iErrorNumber == Errors.UploadedFileRenamed || iErrorNumber == Errors.UploadedInvalidNameRenamed) { response.Clear(); } #else response.Clear(); #endif response.Write("<script type=\"text/javascript\">"); response.Write(this.GetJavaScriptCode(iErrorNumber, sFileName, this.CurrentFolder.Url + sFileName)); response.Write("</script>"); response.End(); }
internal void _listener_404(IHttpClientContext context, IHttpRequest request, IHttpResponse response) { HttpJob httpJob = new HttpJob(this, context, request, response); lock (HttpJobs) { HttpJobs.Add(httpJob); } // 5 second wait if (Monitor.TryEnter(HttpLock, waitForEachTime)) { DoJob(httpJob); Monitor.Exit(HttpLock); } else { LogInfo("ERROR Waiting for prevoius request more than " + TaskQueueHandler.GetTimeString(waitForEachTime)); httpJob.OutOfLock = true; DoJob(httpJob); } }
private void ExportarExcelPlantilla(System.Web.HttpResponse Response) { ExpedienteBLL capanegocios = new ExpedienteBLL(); ExpedienteBE objeto = new ExpedienteBE(); DataTable dtExpediente = new DataTable(); try { if (txtFilExpediente.Text.Trim() != string.Empty) { objeto.CodigoExpediente = txtFilExpediente.Text.Trim(); } else { objeto.CodigoExpediente = "*"; } if (txtFilCotizacion.Text.Trim() != string.Empty) { objeto.CodigoCotizacion = txtFilCotizacion.Text.Trim(); } else { objeto.CodigoCotizacion = "*"; } objeto.IdTipoCliente = Convert.ToInt32(ddlFilTipoCliente.SelectedValue); if (txtFilCliente.Text.Trim() != string.Empty) { objeto.Cliente = txtFilCliente.Text.Trim(); } else { objeto.Cliente = "*"; } objeto.Producto = txtFilProducto.Text.Trim(); if (txtFilFecCotiz.Text == string.Empty) { objeto.FechaCotizacion = Convert.ToDateTime(doMain.Utils.FechaNulaUtils.FechaNula()); } else { objeto.FechaCotizacion = Convert.ToDateTime(txtFilFecCotiz.Text); } objeto.FechaIngreso = Convert.ToDateTime(doMain.Utils.FechaNulaUtils.FechaNula()); objeto.IdEstado = Convert.ToInt32(ddlFilEstado.SelectedValue); objeto.IdEnsayo = Convert.ToInt32(ddlFilEnsayo.SelectedValue); objeto.IdAnalista = Convert.ToInt32(ddlFilAnalista.SelectedValue); objeto.IdProcedencia = Convert.ToInt32(Constante.Numeros.Cero); var lstExpediente = new ExpedienteBLL().ExportExpediente(objeto); //crear datatable para enviar al metodo de descarga var dataTableDescargar = new System.Data.DataTable(Guid.NewGuid().ToString()); var Expediente = new DataColumn("Expediente", typeof(string)); var Cliente = new DataColumn("Cliente", typeof(string)); var TipoCliente = new DataColumn("TipoCliente", typeof(string)); var Producto = new DataColumn("Producto", typeof(string)); var Lote = new DataColumn("Lote", typeof(string)); var DCI = new DataColumn("DCI", typeof(string)); var Clasificacion = new DataColumn("Clasificacion", typeof(string)); var Red = new DataColumn("Red", typeof(string)); var Norma = new DataColumn("Norma", typeof(string)); var Estado = new DataColumn("Estado", typeof(string)); var FechaIngreso = new DataColumn("FechaIngreso", typeof(string)); var FechaIngresoSIGEL = new DataColumn("FechaIngresoSIGEL", typeof(string)); dataTableDescargar.Columns.AddRange(new DataColumn[] { Expediente, Cliente, TipoCliente, Producto, Lote, DCI, Clasificacion, Red, Norma, Estado, FechaIngreso, FechaIngresoSIGEL }); //Llenar data al datatable foreach (ExpedienteBE oExpediente in lstExpediente) { DataRow RowFile = dataTableDescargar.NewRow(); RowFile["Expediente"] = oExpediente.CodigoExpediente; RowFile["Cliente"] = oExpediente.Cliente; RowFile["TipoCliente"] = oExpediente.TipoCliente; RowFile["Producto"] = oExpediente.Producto; RowFile["Lote"] = oExpediente.Lote; RowFile["DCI"] = oExpediente.DCI; RowFile["Clasificacion"] = oExpediente.Clasificacion; RowFile["Red"] = oExpediente.Red; RowFile["Norma"] = oExpediente.Norma; RowFile["Estado"] = oExpediente.Estado; if (oExpediente.FechaIngreso != Convert.ToDateTime("01/01/1901")) { RowFile["FechaIngreso"] = string.Format("{0:d}", oExpediente.FechaIngreso); } else { RowFile["FechaIngreso"] = string.Empty; } if (oExpediente.FechaIngresoSIGEL != Convert.ToDateTime("01/01/1901")) { RowFile["FechaIngresoSIGEL"] = string.Format("{0:d}", oExpediente.FechaIngresoSIGEL); } else { RowFile["FechaIngresoSIGEL"] = string.Empty; } dataTableDescargar.Rows.Add(RowFile); } ExportarUtils ObjExporExcel = new ExportarUtils(); object[] pNombreCabeceras = new object[] { "Expediente", "Cliente", "Tipo Cliente", "Producto", "Lote", "DCI", "Clasificacion", "Red", "Norma", "Estado", "Fecha Ingreso", "Fecha Ingreso SIGEL" }; object[] pEstilos = new object[] { new object[] { 11, OleDbType.Date }, new object[] { 12, OleDbType.Date } }; string MessageOut = ObjExporExcel.DescargarDataTableToExcel(dataTableDescargar, "Archivo Seguimiento Expediente", pNombreCabeceras, pEstilos, Page.Response); if (MessageOut != "OK") { //objMsgBox.MsgBoxCC(lblMensaje, MessageOut, "Error"); } } catch (Exception ex) { errores = ex.Message; } }
public void BlockingHandler(IHttpClientContext context0, IHttpRequest request, IHttpResponse response) { // UUID capsID; bool success; string path = request.Uri.PathAndQuery;//.TrimEnd('/'); if (path.Contains("5580")) { path = path.Replace("?:5580/", ""); } string pathd = HttpUtility.UrlDecode(path);//.TrimEnd('/'); LogInfo("_listener " + path + " from " + request.RemoteEndPoint); if (request.UriPath.EndsWith(".ico")) { response.Status = HttpStatusCode.NotFound; response.Send(); } var wrresp = new WriteLineToResponse(this, response); string botname = GetVariable(request, "bot", GetVariable(request, "botid", null)); ScriptExecutor _botClient = clientManager.GetScriptExecuter(botname); if (_botClient == null) { response.Status = HttpStatusCode.ServiceUnavailable; response.Send(); return; } // Micro-posterboard if (pathd.StartsWith("/posterboard")) { string slot = path; string value = ""; value = _botClient.getPosterBoard(slot) as string; if (value != null) { if (value.Length > 0) { LogInfo(String.Format(" board response: {0} = {1}", slot, value)); } } AddToBody(response, "<xml>"); AddToBody(response, "<slot>"); AddToBody(response, "<path>" + path + "</path>"); AddToBody(response, "<value>" + (value ?? "") + "</value>"); AddToBody(response, "</slot>"); AddToBody(response, "</xml>"); wrresp.response = null; response.Status = HttpStatusCode.OK; response.Send(); return; } bool useHtml = false; if (request.Method == "POST") { var fdp = new FormDecoderProvider(); fdp.Add(new MultipartDecoder()); fdp.Add(new UrlDecoder()); request.DecodeBody(fdp); } if (path.StartsWith("/?") || path.StartsWith("/test")) { useHtml = true; } if (DLRConsole.IsDougsMachine) { useHtml = true; } try { if (OverrideHandlers(request, response)) { return; } if (useHtml) { AddToBody(response, "<html>"); AddToBody(response, "<head>"); botname = GetVariable(request, "bot", _botClient.GetName()); AddToBody(response, "<title>" + botname + "</title>"); AddToBody(response, "</head>"); AddToBody(response, "<body>"); AddToBody(response, "<pre>"); foreach (var p in request.Param.AsEnumerable()) { foreach (var item in p.Values) { AddToBody(response, "" + p.Name + " = " + item); } } AddToBody(response, "</pre>"); AddToBody(response, "<a href='" + request.Uri.PathAndQuery + "'>" + request.Uri.PathAndQuery + "</a>"); AddToBody(response, "<pre>"); } string cmd = GetVariable(request, "cmd", "MeNe"); CmdResult res; // this is our default handler if (cmd != "MeNe") { res = _botClient.ExecuteXmlCommand(cmd + " " + GetVariable(request, "args", ""), request, wrresp.WriteLine); } else { try { InvokeAsMene(request, response, _botClient, pathd, wrresp); } catch (Exception exception) { LogInfo("InvokeAsMene exception: " + exception); } } if (useHtml) { AddToBody(response, "</pre>"); AddToBody(response, "</body>"); AddToBody(response, "</html>"); } } finally { wrresp.response = null; response.Status = HttpStatusCode.OK; try { response.Send(); } catch (Exception e) { LogInfo("Exception sening respose: " + e); } } }
public void ProcessRequest(HttpContext context) { System.Web.HttpRequest Request = context.Request; System.Web.HttpResponse Response = context.Response; int itemId = -1, qty = 1; if (Request.Form["ItemId"] != null) { try { itemId = Int32.Parse(Request.Form["ItemId"]); } catch { } } else { if (Request.QueryString["ItemId"] != null) { try { itemId = Int32.Parse(Request.QueryString["ItemId"]); } catch { } } } if (Request.Form["QTY"] != null) { try { qty = Int32.Parse(Request.Form["QTY"]); } catch { } } else { if (Request.QueryString["QTY"] != null) { try { qty = Int32.Parse(Request.QueryString["QTY"]); } catch { } } } lw.ShoppingCart.ShoppingCart sCart = new lw.ShoppingCart.ShoppingCart(); sCart.Empty(); string optionsKey = Request["Options"]; optionsKey = String.IsNullOrEmpty(optionsKey)? "": optionsKey; ChoicesMgr cMgr = new ChoicesMgr(); if (optionsKey == "") { DataTable dt = cMgr.GetItemOptions(itemId); if (dt.Rows.Count > 0) { Config cfg = new Config(); ItemsMgr iMgr = new ItemsMgr(); DataRow item = iMgr.GetItem(itemId); string ProductDetailsFolder = cfg.GetKey("ProductDetailsFolder"); string red = string.Format("{2}/{1}/{0}.aspx", item["UniqueName"], ProductDetailsFolder, WebContext.Root ); Response.Redirect(red + "?err=" + lw.CTE.Errors.SelectItemOptions); } } sCart.AddItem(itemId, qty, optionsKey, "", ""); Response.Redirect(WebContext.Root + "/shopping-cart/"); }
internal WriteLineToResponse(JobGiver server, IHttpResponse r) { response = r; Server = server; }
protected void Page_Init(object sender, EventArgs e) { try { var culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"); culture.NumberFormat.CurrencySymbol = string.Empty; System.Threading.Thread.CurrentThread.CurrentCulture = culture; System.Threading.Thread.CurrentThread.CurrentUICulture = culture; base.InitializeCulture(); string lcomp = Server.MapPath("~/Facturacion/Electronica/Reportes/Iva_Compras.xsd"); System.IO.File.Copy(lcomp, @System.IO.Path.GetTempPath() + "Iva_Compras.xsd", true); oRpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); bool HayME = false; string reportPath = ""; if (Session["monedasExtranjeras"] != null) { HayME = (bool)Session["monedasExtranjeras"]; } if (!HayME) { reportPath = Server.MapPath("~/Facturacion/Electronica/Reportes/IvaComprasCR.rpt"); } else { reportPath = Server.MapPath("~/Facturacion/Electronica/Reportes/IvaComprasMECR.rpt"); } oRpt.Load(reportPath); Entidades.IvaCompras ivaCompras = new Entidades.IvaCompras(); if (Session["ivaCompras"] != null) { ivaCompras = (Entidades.IvaCompras)Session["ivaCompras"]; DataSet ds = new DataSet(); XmlSerializer objXS = new XmlSerializer(ivaCompras.GetType()); StringWriter objSW = new StringWriter(); objXS.Serialize(objSW, ivaCompras); StringReader objSR = new StringReader(objSW.ToString()); ds.ReadXml(objSR); oRpt.SetDataSource(ds); } else { Response.Redirect("~/Facturacion/Electronica/Reportes/IvaComprasFiltros.aspx", true); } string formatoRptExportar = ""; if (Session["formatoRptExportar"] != null) { formatoRptExportar = (string)Session["formatoRptExportar"]; } if (Session["mostrarFechaYHora"] != null) { if ((bool)Session["mostrarFechaYHora"] == false) { oRpt.DataDefinition.FormulaFields["MostrarFechaYHora"].Text = "'N'"; } } oRpt.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperLetter; oRpt.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Landscape; oRpt.DataDefinition.FormulaFields["RazSoc"].Text = "'" + ((Entidades.Sesion)Session["Sesion"]).Cuit.RazonSocial + "'"; if (formatoRptExportar == "") { CrystalReportViewer1.GroupTreeStyle.ShowLines = false; CrystalReportViewer1.HasToggleGroupTreeButton = false; CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None; CrystalReportViewer1.ReportSource = oRpt; CrystalReportViewer1.HasPrintButton = true; } else { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(ivaCompras.Cuit); sb.Append("-"); sb.Append(Convert.ToDateTime(ivaCompras.PeriodoDsd).ToString("yyyyMMdd")); sb.Append("-"); sb.Append(Convert.ToDateTime(ivaCompras.PeriodoHst).ToString("yyyyMMdd")); if (formatoRptExportar == "PDF") { CrystalDecisions.Shared.ExportOptions exportOpts = new CrystalDecisions.Shared.ExportOptions(); CrystalDecisions.Shared.PdfRtfWordFormatOptions pdfOpts = CrystalDecisions.Shared.ExportOptions.CreatePdfRtfWordFormatOptions(); exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat; exportOpts.ExportFormatOptions = pdfOpts; oRpt.ExportToHttpResponse(exportOpts, Response, true, sb.ToString()); } if (formatoRptExportar == "Excel") { CrystalDecisions.Shared.ExportOptions exportOpts = new CrystalDecisions.Shared.ExportOptions(); CrystalDecisions.Shared.ExcelFormatOptions pdfOpts = CrystalDecisions.Shared.ExportOptions.CreateExcelFormatOptions(); exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat; exportOpts.ExportFormatOptions = pdfOpts; oRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Excel, Server.MapPath("~/TempExcel/") + sb.ToString() + ".xls"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment; filename=" + sb.ToString() + ".xls" + ";"); response.TransmitFile(Server.MapPath("~/TempExcel/" + sb.ToString() + ".xls")); response.Flush(); response.End(); } } } catch (System.Threading.ThreadAbortException) { Trace.Warn("Thread abortado"); } catch (Exception ex) { WebForms.Excepciones.Redireccionar(ex, "~/NotificacionDeExcepcion.aspx"); } }
static internal void AddToBody(IHttpResponse response, string text) { #if USE_HTTPSERVER_DLL response.AddToBody(text + Environment.NewLine); #endif }
internal HttpJob(JobGiver server, IHttpClientContext context, IHttpRequest request, IHttpResponse response) { this.Server = server; this.Context = context; this.Request = request; this.Response = response; Thread = Thread.CurrentThread; #if USE_HTTPSERVER_DLL Name = request.UriPath; #endif }
public DB2Excel() { objHttpResponse = System.Web.HttpContext.Current.Response; }