public void Dispose() { Marshal.FinalReleaseComObject(this.Worksheet); }
internal ConnectionPointCookie(object source, object sink, Type eventInterface) { Exception ex = null; if (source is UnsafeNativeMethods.IConnectionPointContainer) { UnsafeNativeMethods.IConnectionPointContainer cpc = (UnsafeNativeMethods.IConnectionPointContainer)source; try { Guid tmp = eventInterface.GUID; if (cpc.FindConnectionPoint(ref tmp, out connectionPoint) != NativeMethods.S_OK) { connectionPoint = null; } } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } connectionPoint = null; } if (connectionPoint == null) { ex = new ArgumentException(SR.Get(SRID.AxNoEventInterface, eventInterface.Name)); } // IsComObject(sink): this is the case of a managed sink object wrapped in IDispatchSTAForwarder - // see WebBrowser.CreateSink(). else if (sink == null || !eventInterface.IsInstanceOfType(sink) && !Marshal.IsComObject(sink)) { ex = new InvalidCastException(SR.Get(SRID.AxNoSinkImplementation, eventInterface.Name)); } else { int hr = connectionPoint.Advise(sink, ref cookie); if (hr != NativeMethods.S_OK) { cookie = 0; Marshal.FinalReleaseComObject(connectionPoint); connectionPoint = null; ex = new InvalidOperationException(SR.Get(SRID.AxNoSinkAdvise, eventInterface.Name, hr)); } } } else { ex = new InvalidCastException(SR.Get(SRID.AxNoConnectionPointContainer)); } if (connectionPoint == null || cookie == 0) { if (connectionPoint != null) { Marshal.FinalReleaseComObject(connectionPoint); } if (ex == null) { throw new ArgumentException(SR.Get(SRID.AxNoConnectionPoint, eventInterface.Name)); } else { throw ex; } } }
private void button2_Click(object sender, EventArgs e) { Excel.Application app; Excel.Worksheet wsh; Excel.Workbook book; app = new Excel.Application(); book = app.Workbooks.Add(); wsh = (Excel.Worksheet)book.Worksheets.get_Item(1); wsh.Name = "Menu"; DataTable dt_menu = main.db.getDb("menu"); DataTable dt_menufood = main.db.getDb("menufood"); DataColumn[] key = { dt_menu.Columns["menuid"] }; dt_menu.PrimaryKey = key; foreach (DataRow a in dt_menu.Rows) { a.SetField("isShow", "N"); } for (int i = 0; i < numofrow; i++) { Label lab = (Label)tableLayoutPanel1.GetControlFromPosition(0, i); dt_menu.Rows.Find(lab.Tag).SetField("isShow", "Y"); for (int k = 0; k < dt_menufood.Rows.Count; k++) { if (dt_menufood.Rows[k]["menuid"].ToString().Equals(lab.Tag.ToString())) { dt_menufood.Rows[k].Delete(); dt_menufood.AcceptChanges(); k--; } } Label lab2 = (Label)tableLayoutPanel1.GetControlFromPosition(1, i); String[] split = { " " }; String[] temp = lab2.Tag.ToString().Split(split, StringSplitOptions.RemoveEmptyEntries); foreach (String a in temp) { DataRow row = dt_menufood.NewRow(); row["menuid"] = lab.Tag; row["ftypeid"] = a; row["many"] = 1; dt_menufood.Rows.Add(row); } } genXMLData(dt_menu, wsh); wsh = (Excel.Worksheet)book.Worksheets.Add(); wsh.Name = "MenuFood"; genXMLData(dt_menufood, wsh); String s = SaveFilePath(); String appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath); for (int i = 1; i < book.Worksheets.Count + 1; i++) { Excel.Worksheet wsh1; wsh1 = (Excel.Worksheet)book.Worksheets.get_Item(i); wsh1.Columns.AutoFit(); Marshal.FinalReleaseComObject(wsh1); } book.SaveAs(appPath + "\\menu\\" + s + "\\" + fileName); if (wsh != null) { Marshal.FinalReleaseComObject(wsh); } if (book != null) { book.Close(false); //忽略尚未存檔內容,避免跳出提示卡住 Marshal.FinalReleaseComObject(book); } if (app != null) { app.Workbooks.Close(); app.Quit(); Marshal.FinalReleaseComObject(app); } MessageBox.Show("Save"); }
public static void ReleaseCom(Object ComObject) { Marshal.FinalReleaseComObject(ComObject); }
protected override bool Internal_ExcelCancel_Parsing(string filepath) { try { Microsoft.Office.Interop.Excel.Application ap = null; Workbook wb = null; Worksheet ws = null; HKExcelHelper.GetWorkSheet(filepath, ref ap, ref wb, ref ws); Range tRange = null; Int32 nCurrentRow = 2; Int32 CouponColumn = 2; Int32 CancelCountColumn = 18; Int32 StateColumn = 22; while (true) { try { tRange = ws.Cells[nCurrentRow, CouponColumn]; if (tRange == null) { break; } CCancelData pCCancelData = new CCancelData(); pCCancelData.channelOrderCode_ = Convert.ToString(tRange.Value2); if (string.IsNullOrEmpty(pCCancelData.channelOrderCode_) == true) { break; } // 혹시 중복해서 엑셀파일을 다운로드 받았다면 중복이 있을수 있다. 이건 그냥 지나쳐야 한다. if (Excel_Cancel_List_.ContainsKey(pCCancelData.channelOrderCode_) == true) { break; } tRange = ws.Cells[nCurrentRow, CancelCountColumn]; pCCancelData.CancelCount_ = Convert.ToInt32(tRange.Value2); tRange = ws.Cells[nCurrentRow, StateColumn]; pCCancelData.State_ = Convert.ToString(tRange.Value2); for (Int32 i = 1; i <= pCCancelData.CancelCount_; i++) { CCancelData tempExcelData = new CCancelData(); tempExcelData.channelOrderCode_ = string.Format("{0}_{1}", pCCancelData.channelOrderCode_, i); tempExcelData.State_ = pCCancelData.State_; tempExcelData.CancelCount_ = 1; Excel_Cancel_List_.Add(tempExcelData.channelOrderCode_, tempExcelData); } } catch (System.Exception ex) { NewLogManager2.Instance.Log(string.Format("Internal_ExcelCancel_Parsing 엑셀 파싱 에러 : {0}/{1}", filepath, ex.Message)); nCurrentRow++; continue; } nCurrentRow++; } wb.Close(false, Type.Missing, Type.Missing); ap.Quit(); Marshal.FinalReleaseComObject(ws); Marshal.FinalReleaseComObject(wb); Marshal.FinalReleaseComObject(ap); ws = null; wb = null; ap = null; GC.Collect(); } catch (System.Exception ex) { NewLogManager2.Instance.Log(string.Format("Error public override bool Internal_ExcelCancel_Parsing - {0}", ex.Message)); return(false); } return(true); }
public void FinalReleaseComObject_NonComObject_ThrowsArgumentException() { AssertExtensions.Throws <ArgumentException>("o", () => Marshal.FinalReleaseComObject(10)); }
private async void ReadAndJoinExcells() { int startingRowIndex = 1; bool isFirst = true; int FileSizeIndex = 0; int maxfileSize = excellFilePaths.Count; Application application = null; Workbooks wbooks = null; Worksheet destinationSheet = null; Workbook destinationWorkbook = null; try { WriteConsole("Kopyalama Başlıyor..."); await Task.Run(() => { //Instantiate the application object application = new Application(); application.CutCopyMode = (Microsoft.Office.Interop.Excel.XlCutCopyMode) 0; wbooks = application.Workbooks; object misValue = System.Reflection.Missing.Value; destinationWorkbook = wbooks.Add(misValue); destinationSheet = (Worksheet)destinationWorkbook.Worksheets.get_Item(1); //Copy Excel worksheet from source workbook to the destination workbook }); foreach (var item in excellFilePaths) { FileSizeIndex++; WriteConsole($" {FileSizeIndex}/{maxfileSize} {item.FileName} Kopyalanıyor..."); await Task.Run(() => { Workbook sourceWorkbook = wbooks.Open(item.Path); Worksheet wsheet = (Worksheet)sourceWorkbook.Worksheets.get_Item(1); if (isFirst) { startingRowIndex = 1; } else { startingRowIndex = 2; } var usedRange = wsheet.UsedRange; usedRange.Cells[1, 1].Copy(); usedRange.Range[usedRange[startingRowIndex, 1], usedRange[usedRange.Rows.Count, usedRange.Columns.Count]].Copy(); if (isFirst) { destinationSheet.Paste(destinationSheet.UsedRange.Cells[1, 1]); isFirst = false; } else { destinationSheet.Paste(destinationSheet.UsedRange.Cells[destinationSheet.UsedRange.Rows.Count + 1, 1]); } sourceWorkbook?.Close(); Marshal.ReleaseComObject(sourceWorkbook); }); } WriteConsole("Çıktı oluşturuluyor..."); //Save the file await Task.Run(() => { destinationWorkbook.SaveAs(outFile.Path, AccessMode: XlSaveAsAccessMode.xlShared); }); } catch { } finally { WriteConsole("Çıktın Hazır :) Güle güle kullan..."); try { destinationWorkbook?.Close(); Marshal.ReleaseComObject(destinationWorkbook); wbooks?.Close(); Marshal.ReleaseComObject(wbooks); application?.Quit(); Marshal.FinalReleaseComObject(application); } catch (Exception) { } application = null; } }
public void convertPDFToWord(frmMain mainApp, string inFile, string outFile) { // Initialise MS Word variables Word.Application oWord = null; Word.Documents oDocs = null; Word.Document oDoc = null; // Try to run word and open document try { // Start Word mainApp.statusUpdate2("(Starting Word)"); oWord = new Word.Application(); oWord.Visible = false; oWord.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; if (oWord == null) { MessageBox.Show("Word could not be started. Please check that it is installed correctly and allows automation."); Debug.WriteLine("Word could not be started. Check that compiled app reference matches Office version installed."); return; } else { Debug.WriteLine("Word.Application is started"); } mainApp.pbUpdate(20, frmMain.pbModeIncrement); /* * Check MS Word interop version (Interop version is not always the only installed version, but close enough) * Incompatible: * Office 2003: 11.0 * Office 2007: 12.0 * Office 2010: 14.0 * Native PDF conversion available starting from: * Office 2013: 15.0 * Office 2016: 16.0 * */ mainApp.statusUpdate2("(Checking Word Compatibility)"); string msWordVersion = oWord.Application.Version; Debug.WriteLine("MS Word Version: " + msWordVersion); if (Convert.ToDouble(msWordVersion) > 14) { Debug.WriteLine("MS Word Version is newer than 2013. Native PDF conversion available."); } else { MessageBox.Show("It appears that the installed version of Microsoft Word does not support native PDF conversion. Word 2013 or greater is required."); } // Call subroutine to check/set registry value for MS Word silent PDF conversion // TODO: Test before uncommenting for production this.setWordPDFConversionSilent(msWordVersion); mainApp.pbUpdate(20, frmMain.pbModeIncrement); // Open Word document mainApp.statusUpdate2("(Opening PDF and converting to Word)"); oDoc = oWord.Documents.Open(inFile, false, true); Debug.WriteLine("Word.Document is opened"); mainApp.pbUpdate(20, frmMain.pbModeIncrement); // PDF automatic converts to Word format on open // We can now save the document mainApp.statusUpdate2("(Saving as Word document)"); oDoc.SaveAs2(outFile, Word.WdSaveFormat.wdFormatDocumentDefault); mainApp.pbUpdate(20, frmMain.pbModeIncrement); // Clean up and close apps // TODO: Need to test if this also closes user's other windows!!! mainApp.statusUpdate2("(Closing Word)"); Debug.WriteLine("Cleaning up..."); mainApp.pbUpdate(20, frmMain.pbModeIncrement); oDoc.Close(false, Type.Missing, Type.Missing); //oWord.Documents.Close(false, Type.Missing, Type.Missing); oWord.Quit(false, Type.Missing, Type.Missing); } catch (Exception ex) { Debug.WriteLine("Error:{0}", ex.Message); } finally { // Clean up the unmanaged Word/Excel COM resources by explicitly calling Marshal.FinalReleaseComObject on all accessor objects. if (oDoc != null) { Marshal.FinalReleaseComObject(oDoc); oDoc = null; } if (oDocs != null) { Marshal.FinalReleaseComObject(oDocs); oDocs = null; } if (oWord != null) { Marshal.FinalReleaseComObject(oWord); oWord = null; } } }
/// <summary> /// Send Mail /// </summary> /// <returns></returns> public NotifyComResponse Send() { NotifyComResponse notifyComResponse = new NotifyComResponse(); try { try { MailAddress ma = new MailAddress(_fromAddress); } catch (FormatException ex) { // invalid from mail address, set it to [email protected] LogBook.Write("The format for the from email address (" + _fromAddress + ") is incorrect. [email protected] will be used instead."); _fromAddress = "*****@*****.**"; } SmtpClient ss = new SmtpClient(_smtpServer, _smtpPort); MailMessage mm = new MailMessage(_fromAddress, _toAddress, _subject, _body); CDO.Message message = new CDO.Message(); /*Create Mail Message Object*/ MailMessage mailObj = new MailMessage(); /*Email from address*/ mailObj.From = new MailAddress(_fromAddress, _fromName); /*Email to address*/ mailObj.To.Add(new MailAddress(_toAddress)); /*Email subject*/ mailObj.Subject = _subject; /*Email Body Encoding*/ mailObj.BodyEncoding = Encoding.Default; /*Email Body*/ mailObj.Body = _body; /*Body format (HTML/Text)*/ mailObj.IsBodyHtml = _isBodyHTML; /*Via SMTP Gateway (i.e. your local Exchange Server)-> SmtpSendMethod = 0*/ /*Via Direct Domain SMTP Connection w/DNS MX Lookup-> SmtpSendMethod = 1*/ /*When SmtpSendMethod = 1 we are sending via local host instead of using SMTP settings*/ SmtpClient smtpClientObj = null; if (_sendMethod == 1) { //Send message string domain = mailObj.To[0].Address.Substring(mailObj.To[0].Address.IndexOf('@') + 1); //To Do :need to check for MX record existence before you send. Left intentionally for you. string mxRecord = SendSMTP.DnsLookUp.GetMXRecords(domain)[0]; smtpClientObj = new SmtpClient(mxRecord); } else { if (_isTLS == true && _isSSL == false) { ss.EnableSsl = true; ss.Timeout = 20000; ss.DeliveryMethod = SmtpDeliveryMethod.Network; ss.UseDefaultCredentials = false; ss.Credentials = new NetworkCredential(_smtpAuthUserName, _smtpAuthPassword); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; mm.IsBodyHtml = _isBodyHTML; } else { CDO.IConfiguration configuration = message.Configuration; ADODB.Fields fields = configuration.Fields; ADODB.Field field = fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"]; field.Value = _smtpServer; field = fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"]; field.Value = _smtpPort; field = fields["http://schemas.microsoft.com/cdo/configuration/sendusing"]; field.Value = CDO.CdoSendUsing.cdoSendUsingPort; field = fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"]; if (_smtpAuthMethod == "" || _smtpAuthMethod.ToUpper() == "NONE") { field.Value = CDO.CdoProtocolsAuthentication.cdoAnonymous; } else if (_smtpAuthMethod.ToUpper() == "NTLM") { field.Value = CDO.CdoProtocolsAuthentication.cdoNTLM; } else { field.Value = CDO.CdoProtocolsAuthentication.cdoBasic; } field = fields["http://schemas.microsoft.com/cdo/configuration/sendusername"]; field.Value = _smtpAuthUserName; field = fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"]; field.Value = _smtpAuthPassword; field = fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]; field.Value = _isSSL; field = fields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"]; field.Value = 10; fields.Update(); message.From = @"""" + _fromName + @""" <" + _fromAddress + ">";; message.To = _toAddress; message.Subject = _subject; if (_isBodyHTML) { message.HTMLBody = _body; } else { message.TextBody = _body; } } } try { if (_sendMethod == 1) { smtpClientObj.Send(mailObj); } else { /*Send Mail*/ if (_isTLS == true && _isSSL == false) { ss.Send(mm); } else { message.Send(); } } /*Record notify response*/ notifyComResponse.IsError = false; notifyComResponse.IsSucceeded = true; notifyComResponse.ResponseContent = "Email sent to: " + "[" + _emailToName + "]" + _toAddress + ((_isAlphaPager) ? " (ALPHA PAGER) " : ""); } catch (Exception ex) { /*Record notify response*/ notifyComResponse.IsError = true; notifyComResponse.IsSucceeded = false; notifyComResponse.ResponseContent = "Email to: " + "[" + _emailToName + "]" + _toAddress + ((_isAlphaPager) ? " (ALPHA PAGER) " : "") + " Failed " + ex.Message; /*Debug Object values for reference*/ LogBook.Debug(notifyComResponse, this); /*Write exception log*/ LogBook.Write("Error has occurred while sending email to ." + _emailToName, ex, "CooperAtkins.NotificationServer.NotifyEngine.Email.EmailClient"); } finally { // Added on 2/19/2012 // Srinivas Rao Eranti // Added try catch to release the message object try { Marshal.FinalReleaseComObject(message); // GC.SuppressFinalize(message); } catch { } } } catch (Exception ex) { /*Record notify response*/ notifyComResponse.IsError = true; notifyComResponse.IsSucceeded = false; notifyComResponse.ResponseContent = "Email to: " + "[" + _emailToName + "]" + _toAddress + ((_isAlphaPager) ? "(ALPHA PAGER)" : "") + " Failed " + ex.Message; /*Debug Object values for reference*/ LogBook.Debug(notifyComResponse, this); /*Write exception log*/ LogBook.Write("Error has occurred while preparing SMTP setting.", ex, "CooperAtkins.NotificationServer.NotifyEngine.Email.EmailClient"); } return(notifyComResponse); }
public void Dispose() { Marshal.FinalReleaseComObject(writer); }
private void LoadFile(string fileName) { this.Cursor = Cursors.WaitCursor; Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.Visible = false; Workbook workbook = excelApp.Workbooks.Open(fileName); //select the first sheet Worksheet worksheet = (Worksheet)workbook.Worksheets[1]; //find the used range in worksheet Range excelRange = worksheet.UsedRange; object[,] valueArray = excelRange.Value2; int rows = excelRange.Rows.Count; int cols = excelRange.Columns.Count; //clean up stuffs workbook.Close(false); Marshal.ReleaseComObject(workbook); excelApp.Quit(); Marshal.FinalReleaseComObject(excelApp); OleDbCommand cmd = new OleDbCommand("", MainForm.connection); tempTable = "TEMP_" + MainForm.userName.ToUpper(); MainForm.tempTableCreate(tempTable, "create table " + tempTable + " (TEMP_ID counter Primary key, VESSEL_NAME varchar(255), VESSEL_IMO varchar(255), LAST_DATE DateTime)"); int vslCol = 1; int imoCol = 2; int dateCol = 10; int lineCounter = 0; string cmdText = ""; for (int row = 2; row <= rows; row++) { lineCounter++; if (lineCounter < 10) { if (cmdText.Length == 0) { cmdText = "select TOP 1 \n" + "'" + MainForm.StrToSQLStr(valueArray[row, vslCol].ToString()) + "' as VESSEL_NAME,'" + MainForm.StrToSQLStr(valueArray[row, imoCol].ToString()) + "' as VESSEL_IMO," + MainForm.DateTimeToQueryStr(DateTime.FromOADate(Convert.ToDouble(valueArray[row, dateCol]))) + " as LAST_DATE \n" + "from OPTIONS"; } else { cmdText = cmdText + "\n union \n" + "select TOP 1 \n" + "'" + MainForm.StrToSQLStr(valueArray[row, vslCol].ToString()) + "','" + MainForm.StrToSQLStr(valueArray[row, imoCol].ToString()) + "'," + MainForm.DateTimeToQueryStr(DateTime.FromOADate(Convert.ToDouble(valueArray[row, dateCol]))) + " \n" + "from OPTIONS"; } } else { cmdText = cmdText + "\n union \n" + "select TOP 1 \n" + "'" + MainForm.StrToSQLStr(valueArray[row, vslCol].ToString()) + "','" + MainForm.StrToSQLStr(valueArray[row, imoCol].ToString()) + "'," + MainForm.DateTimeToQueryStr(DateTime.FromOADate(Convert.ToDouble(valueArray[row, dateCol]))) + " \n" + "from OPTIONS"; cmd.CommandText = "insert into " + tempTable + " (VESSEL_NAME, VESSEL_IMO, LAST_DATE) \n" + "select * from (\n" + cmdText + "\n)"; MainForm.cmdExecute(cmd); System.Windows.Forms.Application.DoEvents(); lineCounter = 0; cmdText = ""; } } if (lineCounter > 0) { cmd.CommandText = "insert into " + tempTable + " (VESSEL_NAME, VESSEL_IMO, LAST_DATE) \n" + "select * from (\n" + cmdText + "\n)"; MainForm.cmdExecute(cmd); System.Windows.Forms.Application.DoEvents(); lineCounter = 0; } FillTable(); this.Cursor = Cursors.Default; }
/// <summary> /// Rerurns up to maxEncodings codpages that are assumed to be apropriate /// </summary> /// <param name="input">array containing the raw data</param> /// <param name="maxEncodings">maxiumum number of encodings to detect</param> /// <returns>an array of Encoding with assumed encodings</returns> public static Encoding[] DetectInputCodepages(byte[] input, int maxEncodings) { if (Path.DirectorySeparatorChar == '/') { // unix return(new Encoding[0]); } if (maxEncodings < 1) { throw new ArgumentOutOfRangeException("at least one encoding must be returend", "maxEncodings"); } if (input == null) { throw new ArgumentNullException("input"); } // empty strings can always be encoded as ASCII if (input.Length == 0) { return new Encoding[] { Encoding.ASCII } } ; // expand the string to be at least 256 bytes if (input.Length < 256) { byte[] newInput = new byte[256]; int steps = 256 / input.Length; for (int i = 0; i < steps; i++) { Array.Copy(input, 0, newInput, input.Length * i, input.Length); } int rest = 256 % input.Length; if (rest > 0) { Array.Copy(input, 0, newInput, steps * input.Length, rest); } input = newInput; } List <Encoding> result = new List <Encoding>(); // get the IMultiLanguage" interface MultiLanguage.IMultiLanguage2 multilang2 = new MultiLanguage.CMultiLanguageClass(); if (multilang2 == null) { throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang2"); } try { MultiLanguage.DetectEncodingInfo[] detectedEncdings = new MultiLanguage.DetectEncodingInfo[maxEncodings]; int scores = detectedEncdings.Length; int srcLen = input.Length; // setup options (none) MultiLanguage.MLDETECTCP options = MultiLanguage.MLDETECTCP.MLDETECTCP_NONE; // finally... call to DetectInputCodepage multilang2.DetectInputCodepage(options, 0, ref input[0], ref srcLen, ref detectedEncdings[0], ref scores); // get result if (scores > 0) { for (int i = 0; i < scores; i++) { // add the result result.Add(Encoding.GetEncoding((int)detectedEncdings[i].nCodePage)); } } } finally { Marshal.FinalReleaseComObject(multilang2); } // nothing found return(result.ToArray()); }
public static Encoding[] DetectOutgoingEncodings(string input, int[] preferedEncodings, bool preserveOrder) { if (input == null) { throw new ArgumentNullException("input"); } // empty strings can always be encoded as ASCII if (input.Length == 0) { return new Encoding[] { Encoding.ASCII } } ; List <Encoding> result = new List <Encoding>(); // get the IMultiLanguage3 interface MultiLanguage.IMultiLanguage3 multilang3 = new MultiLanguage.CMultiLanguageClass(); if (multilang3 == null) { throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang3"); } try { int[] resultCodePages = new int[preferedEncodings.Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = Marshal.AllocCoTaskMem(sizeof(uint) * preferedEncodings.Length); IntPtr pDetectedEncs = preferedEncodings == null ? IntPtr.Zero : Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (preferedEncodings != null) { Marshal.Copy(preferedEncodings, 0, pPrefEncs, preferedEncodings.Length); } Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MultiLanguage.MLCPF options = MultiLanguage.MLCPF.MLDETECTF_VALID_NLS | MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; if (preserveOrder) { options |= MultiLanguage.MLCPF.MLDETECTF_PRESERVE_ORDER; } if (preferedEncodings != null) { options |= MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; } // finally... call to DetectOutboundCodePage multilang3.DetectOutboundCodePage(options, input, (uint)input.Length, pPrefEncs, (uint)(preferedEncodings == null ? 0 : preferedEncodings.Length), pDetectedEncs, ref detectedCodepages, ref specialChar); // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); // get the encodings for the codepages for (int i = 0; i < detectedCodepages; i++) { result.Add(Encoding.GetEncoding(theResult[i])); } } } finally { if (pPrefEncs != IntPtr.Zero) { Marshal.FreeCoTaskMem(pPrefEncs); } Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } // nothing found return(result.ToArray()); }
public static string ConvertData(string files) { FileInfo newFile = new FileInfo(files); //if (!Directory.Exists(System.Windows.Forms.Application.StartupPath + @"\Report\")) //Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + @"\Report\"); ApplicationClass excelApplication = new ApplicationClass(); Workbook excelWorkBook = null; excelApplication.Caption = System.Guid.NewGuid().ToString().ToUpper(); string paramSourceBookPath = files;//System.Windows.Forms.Application.StartupPath + @"\" + files;// @"D:\test.xls"; object paramMissing = Type.Missing; string name = Path.GetFileNameWithoutExtension(files); //string paramExportFilePath = System.Windows.Forms.Application.StartupPath + @"\Report\" + name + ".pdf"; string paramExportFilePath = newFile.DirectoryName + @"\\" + name + ".pdf"; //MessageBox.Show(paramExportFilePath); XlFixedFormatType paramExportFormat = XlFixedFormatType.xlTypePDF; XlFixedFormatQuality paramExportQuality = XlFixedFormatQuality.xlQualityStandard; bool paramOpenAfterPublish = false; bool paramIncludeDocProps = true; bool paramIgnorePrintAreas = true; object paramFromPage = Type.Missing; object paramToPage = Type.Missing; try { // Open the source workbook. excelWorkBook = excelApplication.Workbooks.Open(paramSourceBookPath, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing, paramMissing); // Save it in the target format. if (excelWorkBook != null) { excelWorkBook.ExportAsFixedFormat(paramExportFormat, paramExportFilePath, paramExportQuality, paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage, paramToPage, paramOpenAfterPublish, paramMissing); // MessageBox.Show(paramExportFilePath); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); // Respond to the error. } finally { // Close the workbook object. if (excelWorkBook != null) { excelApplication.DisplayAlerts = false; excelWorkBook.Close(false, paramMissing, paramMissing); Marshal.ReleaseComObject(excelWorkBook); Marshal.FinalReleaseComObject(excelWorkBook); excelWorkBook = null; } // Quit Excel and release the ApplicationClass object. if (excelApplication != null) { excelApplication.Quit(); Config.EnsureProcessKilled(IntPtr.Zero, excelApplication.Caption); Marshal.ReleaseComObject(excelApplication); Marshal.FinalReleaseComObject(excelApplication); excelApplication = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return(paramExportFilePath); }
//Create the Excel file from dataset public void Okuri(DataTable ds, string SOKOCD) { string saveFileName = "送り状兼受領書_" + SOKOCD + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"); string templetFile = @"template\送り状兼受領書.xlsx"; SaveFileDialog saveDialog = new SaveFileDialog { Filter = "Excel文件 |*.xlsx", FileName = saveFileName, RestoreDirectory = true }; if (saveDialog.ShowDialog() == DialogResult.OK) { saveFileName = saveDialog.FileName; File.Copy(templetFile, saveFileName, true); Excel.Application excel = new Excel.Application(); Excel.Workbook workbook = excel.Workbooks.Open(saveFileName); Excel.Worksheet worksheet = workbook.Worksheets[1]; excel.Visible = false; try { log.Info("EXEC BEGIN"); var distinctIds = ds.AsEnumerable() .Select(s => new { area = s.Field <string>("AREANM"), homen = s.Field <string>("HOMEN"), //soko = s.Field<string>("SOKONM"), //nukn = s.Field<string>("NUKNNM"), }) .Distinct().ToList(); if (distinctIds.Count > 1) { int no = 0; foreach (var a in distinctIds) { string expression; DataRow[] foundRows; expression = "AREANM = '" + a.area.ToString() + "' AND HOMEN = '" + a.homen.ToString() + "'"; foundRows = ds.Select(expression); worksheet.Name = foundRows[0][11] + "_" + foundRows[0][10]; workbook.Worksheets[1].Name = workbook.Worksheets[1].Name.Split(' ')[0]; worksheet.Cells[1, "H"] = foundRows[0][11]; worksheet.Cells[1, "AD"] = foundRows[0][10]; worksheet.Cells[5, "B"] = foundRows[0][2]; worksheet.Cells[5, "H"] = foundRows[0][5]; worksheet.Cells[5, "N"] = foundRows[0][3]; worksheet.Cells[5, "Y"] = foundRows[0][1]; worksheet.Cells[5, "AS"] = foundRows[0][6]; worksheet.Cells[5, "AW"] = foundRows[0][7]; worksheet.Cells[5, "BC"] = foundRows[0][8]; worksheet.Cells[5, "BM"] = foundRows[0][9]; worksheet.Cells[5, "CD"] = foundRows[0][12]; worksheet.Cells[5, "CN"] = "サイン"; for (int i = 0; i < foundRows.Length - 1; i++) { Excel.Range RngToCopy = worksheet.get_Range("B5").EntireRow; Excel.Range RngToInsert = worksheet.get_Range("B" + (i + 6)).EntireRow; RngToInsert.Insert(Excel.XlInsertShiftDirection.xlShiftDown, RngToCopy.Copy()); worksheet.Cells[6 + i, "B"] = foundRows[i + 1][2]; worksheet.Cells[6 + i, "H"] = foundRows[i + 1][5]; worksheet.Cells[6 + i, "N"] = foundRows[i + 1][3]; worksheet.Cells[6 + i, "Y"] = foundRows[i + 1][1]; worksheet.Cells[6 + i, "AS"] = foundRows[i + 1][6]; worksheet.Cells[6 + i, "AW"] = foundRows[i + 1][7]; worksheet.Cells[6 + i, "BC"] = foundRows[i + 1][8]; worksheet.Cells[6 + i, "BM"] = foundRows[i + 1][9]; worksheet.Cells[6 + i, "CD"] = foundRows[i + 1][12]; worksheet.Cells[6 + i, "CN"] = "サイン"; } no++; if (no < distinctIds.Count) { worksheet.Copy(workbook.Worksheets[1], Type.Missing); worksheet.get_Range("B5:B1000").EntireRow.ClearContents(); worksheet.get_Range("CN6:CN1000").EntireRow.Borders.LineStyle = Excel.XlLineStyle.xlLineStyleNone; } } } else { foreach (var a in distinctIds) { string expression; DataRow[] foundRows; expression = "AREANM = '" + a.area.ToString() + "' AND HOMEN = '" + a.homen.ToString() + "'"; foundRows = ds.Select(expression); worksheet.Name = foundRows[0][11] + "_" + foundRows[0][10]; workbook.Worksheets[1].Name = workbook.Worksheets[1].Name.Split(' ')[0]; worksheet.Cells[1, "H"] = foundRows[0][11]; worksheet.Cells[1, "AD"] = foundRows[0][10]; worksheet.Cells[5, "B"] = foundRows[0][2]; worksheet.Cells[5, "H"] = foundRows[0][5]; worksheet.Cells[5, "N"] = foundRows[0][3]; worksheet.Cells[5, "Y"] = foundRows[0][1]; worksheet.Cells[5, "AS"] = foundRows[0][6]; worksheet.Cells[5, "AW"] = foundRows[0][7]; worksheet.Cells[5, "BC"] = foundRows[0][8]; worksheet.Cells[5, "BM"] = foundRows[0][9]; worksheet.Cells[5, "CD"] = foundRows[0][12]; worksheet.Cells[5, "CN"] = "サイン"; for (int i = 1; i < foundRows.Length; i++) { Excel.Range RngToCopy = worksheet.get_Range("B5").EntireRow; Excel.Range RngToInsert = worksheet.get_Range("B" + (i + 5)).EntireRow; RngToInsert.Insert(Excel.XlInsertShiftDirection.xlShiftDown, RngToCopy.Copy()); worksheet.Cells[5 + i, "B"] = foundRows[i][2]; worksheet.Cells[5 + i, "H"] = foundRows[i][5]; worksheet.Cells[5 + i, "N"] = foundRows[i][3]; worksheet.Cells[5 + i, "Y"] = foundRows[i][1]; worksheet.Cells[5 + i, "AS"] = foundRows[i][6]; worksheet.Cells[5 + i, "AW"] = foundRows[i][7]; worksheet.Cells[5 + i, "BC"] = foundRows[i][8]; worksheet.Cells[5 + i, "BM"] = foundRows[i][9]; worksheet.Cells[5 + i, "CD"] = foundRows[i][12]; worksheet.Cells[5 + i, "CN"] = "サイン"; } } } } catch (Exception e) { log.Error("ERROR" + e.Message); } finally { excel.DisplayAlerts = false; Application.DoEvents(); workbook.Save(); excel.Quit(); Marshal.FinalReleaseComObject(excel); log.Info("EXEC END"); } } else { MessageBox.Show("処理を中止しました。"); } }
private void backgroundWorkerBurn_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { MsftDiscRecorder2 discRecorder = null; MsftDiscFormat2Data discFormatData = null; IMediaItem mediaItem; try { // // Create and initialize the IDiscRecorder2 object // discRecorder = new MsftDiscRecorder2(); var burnData = (BurnData)e.Argument; mediaItem = burnData.mediaItem; discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId); // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data { Recorder = discRecorder, ClientName = ClientName, ForceMediaToBeClosed = _closeMedia }; // // Set the verification level // var burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = _verificationLevel; // // Check if media is blank, (for RW media) // object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) { multisessionInterfaces = discFormatData.MultisessionInterfaces; } // // Create the file system // IStream fileSystem; if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem, mediaItem)) { e.Result = -1; return; } // // add the Update event handler // discFormatData.Update += discFormatData_Update; // // Write the data here // try { discFormatData.Write(fileSystem); e.Result = 0; } catch (COMException ex) { e.Result = ex.ErrorCode; MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { if (fileSystem != null) { Marshal.FinalReleaseComObject(fileSystem); } } // // remove the Update event handler // discFormatData.Update -= discFormatData_Update; if (_ejectMedia) { discRecorder.EjectMedia(); } } catch (COMException exception) { // // If anything happens during the format, show the message // MessageBox.Show(exception.Message); e.Result = exception.ErrorCode; } finally { if (discRecorder != null) { Marshal.ReleaseComObject(discRecorder); } if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } } }
public void FinalReleaseComObject_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws <PlatformNotSupportedException>(() => Marshal.FinalReleaseComObject(null)); }
/// <summary> /// 获取 vb login 和 .net login /// 可绕过login验证 /// </summary> /// <param name="bd"></param> /// <param name="oSysLogin"></param> /// <param name="u8Login"></param> /// <returns></returns> private Model.DealResult GetU8LoginNew(Model.APIData bd, UFSoft.U8.Framework.Login.UI.clsLogin oSysLogin, U8Login.clsLogin u8Login) { Model.DealResult dr = new Model.DealResult(); System.Diagnostics.Trace.WriteLine(" before GetU8Login 判断格式 "); #region 判断格式 登录 string strErr = ",请在[账套档案注册]模块中更新!"; if (string.IsNullOrEmpty(bd.ConnectInfo.UserId)) { dr.ResultMsg = "默认操作员不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.Source)) { dr.ResultMsg = "数据源不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.AccId)) { dr.ResultMsg = "账套号不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.Srv)) { dr.ResultMsg = "服务器地址不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.YearId)) { dr.ResultMsg = "登陆年度不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } else { try { int.Parse(bd.ConnectInfo.YearId); } catch { dr.ResultMsg = "登陆年度格式错误:" + bd.ConnectInfo.YearId + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } } DbHelperSQLP dsp = new DbHelperSQLP(bd.ConnectInfo.Constring); string strSql = "SELECT 1 FROM UFSystem.dbo.UA_AccountDatabase A JOIN UFSystem.dbo.UA_Account B ON A.cAcc_Id=B.cAcc_Id WHERE A.cAcc_Id='" + bd.ConnectInfo.AccId + "' "; if (!dsp.Exists(strSql)) { dr.ResultMsg = "登陆失败,原因:账套 " + bd.ConnectInfo.AccId + " 在 " + bd.ConnectInfo.Srv + " 上不存在"; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } #endregion System.Diagnostics.Trace.WriteLine(" after GetU8Login 判断格式 "); bool bLogined; string beginDate; oSysLogin = new UFSoft.U8.Framework.Login.UI.clsLogin(); beginDate = ""; //GetMonthBegindate(acc_ID, iYear, "12") //用12期间构造login,12期间必有 oSysLogin.LanguageID = "zh-CN"; // GetAccountLoginLocaleID(modUtility.GetDbName(acc_ID, iYear)) string subId = U8.Interface.Bus.SysInfo.subId; string userId = bd.ConnectInfo.UserId; string accId = bd.ConnectInfo.Source + "@" + bd.ConnectInfo.AccId; string yearId = bd.ConnectInfo.YearId; string password = bd.ConnectInfo.Password; string date = bd.ConnectInfo.Date; string srv = bd.ConnectInfo.sSrv; string serial = bd.ConnectInfo.Serial; bLogined = oSysLogin.login(subId, userId, password, srv, date, accId, serial); if (!bLogined) { strErr = oSysLogin.ErrDescript; //& g_fmtr.GetString("String.U8.AA.Admin.4671", g_args) //'strErr = oSysLogin.ErrDescript & "内置用户密码不正确!" //'Call WriteTransferLog(g_ologin.cAcc_ID, g_ologin.cAccName, g_ologin.cIyear, "", "准备年结环境时出现错误,错误描述:" & oSyslogin.ErrDescript & "内置用户密码不正确!") dr.ResultMsg = "登陆失败,原因:" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } UFSoft.U8.Framework.LoginContext.ProductContext oLoginContext; oLoginContext = new UFSoft.U8.Framework.LoginContext.ProductContext(); oLoginContext = oSysLogin.SubLogin(U8.Interface.Bus.SysInfo.subId); if (null == oLoginContext) { strErr = oSysLogin.ErrDescript; //'MsgBox oSyslogin.ErrDescript //'Call WriteTransferLog(g_ologin.cAcc_ID, g_ologin.cAccName, g_ologin.cIyear, "", "准备年结环境时出现错误,错误描述:" & oSyslogin.ErrDescript) dr.ResultMsg = "登陆失败,原因:" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } //u8Login = new U8Login.clsLogin(); if (!u8Login.ConstructLogin(oSysLogin.userToken)) { strErr = u8Login.ShareString; //'Call WriteTransferLog(g_ologin.cAcc_ID, g_ologin.cAccName, g_ologin.cIyear, "", "准备年结环境时出现错误,错误描述:" & oLogin.ShareString) dr.ResultMsg = "登陆失败,原因:" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (!u8Login.Login(ref subId, ref accId, ref yearId, ref userId, ref password, ref date, ref srv, ref serial)) { System.Diagnostics.Trace.WriteLine(" GetU8Login failed "); dr.ResultMsg = "登陆失败,原因:" + u8Login.ShareString; if (u8Login.ShareString.IndexOf("年度") > 0 || u8Login.ShareString.IndexOf("日期") > 0) { dr.ResultMsg += " - " + date; } dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } return(dr); }
/// <summary> /// Initialize the MediaFoundationProvider with specific file. /// </summary> public MediaFoundationProvider(string url) { MediaFoundationApi.Startup(); if (!File.Exists(url)) { throw new FileNotFoundException("This file doesn't exist"); } MediaFoundationInterop.MFCreateSourceResolver(out IMFSourceResolver resolver); //Creates both IMFMediaSource and IMFByteStream.Uses the stream for 'Read' method and uses the source to collect format information. resolver.CreateObjectFromURL(url, SourceResolverFlags.MF_RESOLUTION_BYTESTREAM | SourceResolverFlags.MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out _, out object _stream); IMFByteStream byteStream = _stream as IMFByteStream; resolver.CreateObjectFromByteStream(byteStream, null, SourceResolverFlags.MF_RESOLUTION_MEDIASOURCE | SourceResolverFlags.MF_RESOLUTION_CONTENT_DOES_NOT_HAVE_TO_MATCH_EXTENSION_OR_MIME_TYPE, null, out _, out object _source); Marshal.FinalReleaseComObject(resolver); IMFMediaSource source = _source as IMFMediaSource; source.CreatePresentationDescriptor(out IMFPresentationDescriptor descriptor); descriptor.GetStreamDescriptorCount(out uint sdcount); for (uint i = 0; i < sdcount; i++) { descriptor.GetStreamDescriptorByIndex(i, out _, out IMFStreamDescriptor sd); sd.GetMediaTypeHandler(out IMFMediaTypeHandler typeHandler); typeHandler.GetMediaTypeByIndex(0, out IMFMediaType mediaType); mediaType.GetMajorType(out Guid streamtype); if (streamtype == MediaTypes.MFMediaType_Audio) { mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND, out int rate);//SampleRate mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS, out int channelcount); int samplesize; try { mediaType.GetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE, out samplesize); } catch (COMException e) { if ((uint)e.HResult != 0xC00D36E6) { throw e; } else { samplesize = 8; } } WaveFormat = new WaveFormat(rate, samplesize, channelcount); } else { continue; } } byteStream.GetLength(out streamlength); byteStream.SetCurrentPosition(0); //Moves all the bytes in IMFByteStream to MemoryStream. MediaFoundationInterop.MFCreateMemoryBuffer(unchecked ((int)streamlength), out IMFMediaBuffer mediabuffer); mediabuffer.Lock(out IntPtr pbuffer, out int length, out _); byteStream.Read(pbuffer, length, out _); byte[] buffer = new byte[length]; Marshal.Copy(pbuffer, buffer, 0, length); datastream = new MemoryStream(buffer); }
/// <summary> /// 获取Login对象 /// </summary> /// <param name="bd"></param> /// <param name="u8Login"></param> /// <returns></returns> public Model.DealResult GetU8Login_bak(Model.APIData bd, U8Login.clsLogin u8Login) { System.Diagnostics.Trace.WriteLine(" begin GetU8Login "); Model.DealResult dr = new Model.DealResult(); #region 一次登录 //if (bd.TaskType != 1 && null != _login) //{ // u8Login = _login; // return dr; //} #endregion System.Diagnostics.Trace.WriteLine(" before GetU8Login 判断格式 "); #region 判断格式 登录 string strErr = ",请在[账套档案注册]模块中更新!"; if (string.IsNullOrEmpty(bd.ConnectInfo.UserId)) { dr.ResultMsg = "默认操作员不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.Source)) { dr.ResultMsg = "数据源不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.AccId)) { dr.ResultMsg = "账套号不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.Srv)) { dr.ResultMsg = "服务器地址不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } if (string.IsNullOrEmpty(bd.ConnectInfo.YearId)) { dr.ResultMsg = "登陆年度不能为空" + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } else { try { int.Parse(bd.ConnectInfo.YearId); } catch { dr.ResultMsg = "登陆年度格式错误:" + bd.ConnectInfo.YearId + strErr; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } } DbHelperSQLP dsp = new DbHelperSQLP(bd.ConnectInfo.Constring); string strSql = "SELECT 1 FROM UFSystem.dbo.UA_AccountDatabase A JOIN UFSystem.dbo.UA_Account B ON A.cAcc_Id=B.cAcc_Id WHERE A.cAcc_Id='" + bd.ConnectInfo.AccId + "' "; if (!dsp.Exists(strSql)) { dr.ResultMsg = "登陆失败,原因:账套 " + bd.ConnectInfo.AccId + " 在 " + bd.ConnectInfo.Srv + " 上不存在"; dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } #endregion System.Diagnostics.Trace.WriteLine(" after GetU8Login 判断格式 "); string subId = U8.Interface.Bus.SysInfo.subId; string userId = bd.ConnectInfo.UserId; string accId = bd.ConnectInfo.Source + "@" + bd.ConnectInfo.AccId; string yearId = bd.ConnectInfo.YearId; string password = bd.ConnectInfo.Password; string date = bd.ConnectInfo.Date; string srv = bd.ConnectInfo.sSrv; string serial = bd.ConnectInfo.Serial; #region 20140814 #endregion System.Diagnostics.Trace.WriteLine(" before GetU8Login u8Login.Login "); System.Diagnostics.Trace.WriteLine(" login parameter : " + subId + "----" + accId + "----" + yearId + "----" + userId + "----" + password + "----" + date + "----" + srv + "----" + serial); try { if (!u8Login.Login(ref subId, ref accId, ref yearId, ref userId, ref password, ref date, ref srv, ref serial)) { System.Diagnostics.Trace.WriteLine(" GetU8Login failed "); dr.ResultMsg = "登陆失败,原因:" + u8Login.ShareString; if (u8Login.ShareString.IndexOf("年度") > 0 || u8Login.ShareString.IndexOf("日期") > 0) { dr.ResultMsg += " - " + date; } dr.ResultNum = -1; Marshal.FinalReleaseComObject(u8Login); throw new Exception(dr.ResultMsg); } } catch (Exception ee) { if (dr.ResultNum == -1) { throw new Exception(dr.ResultMsg); } else { System.Diagnostics.Trace.WriteLine(" GetU8Login u8Login.Login Error : " + ee.StackTrace); dr.ResultNum = -1; throw new Exception(ee.Message); } } System.Diagnostics.Trace.WriteLine(" end GetU8Login u8Login.Login "); System.Diagnostics.Trace.WriteLine(" end GetU8Login "); //_login = u8Login; return(dr); }
public CreateExcelFile(LoadXML x, LoadTemplate t) { XML = x; template = t; try { //Start the Microsoft Excel Application string excelTemplate = System.AppDomain.CurrentDomain.BaseDirectory + "New EBOM " + template.time + ".xlsx"; xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { MessageBox.Show("Excel is not properly installed!!"); return; } xlWorkBooks = xlApp.Workbooks; try { xlWorkBook = xlWorkBooks.Open(excelTemplate, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); //open the template file! } catch (Exception e) { return; } xlWorkSheets = xlWorkBook.Worksheets; xlWorkSheet = xlWorkSheets.get_Item(1); //int totalRows = template.allCells.GetLength(0); //int totalColumns = template.allCells.GetLength(1); //for (int row = 0; row < totalRows ; row++) //{ // for (int column = 0; column < totalColumns; column++) // the plus one is because the excel columns and rows start at 1 // { // if (template.allCells[row, column].text.Contains("[TextHere]")) writeData(template.allCells[row, column]); // } // Console.WriteLine("Finished writing row " + (row + 1)); //} foreach (LoadTemplate.myCell cell in template.titleBlock) { writeData(cell); } foreach (LoadTemplate.myCell cell in template.headerRow) { writeData(cell); } Console.WriteLine("Finished writing Title Block"); for (int a = 0; a < template.bodyRows.Count; a++) { Range range = xlWorkSheet.Range[xlWorkSheet.Cells[template.bodyRows[a][0].rowIndex, template.bodyRows[a][0].columnIndex], xlWorkSheet.Cells[template.bodyRows[a][template.bodyRows[a].Count - 1].rowIndex, template.bodyRows[a][template.bodyRows[a].Count - 1].columnIndex]]; // get whole row range.Interior.Color = template.bodyColors[a % template.bodyColors.Count]; // change color of whole row if (template.bodyRows[a][template.bodyRows[a].Count - 1].rightLineStyle != XlLineStyle.xlLineStyleNone) // check if we need to set borders { for (int b = 0; b < template.bodyRows[a].Count; b++) //set borders { xlWorkSheet.Cells[template.bodyRows[a][b].rowIndex, template.bodyRows[a][b].columnIndex].Borders(XlBordersIndex.xlEdgeRight).LineStyle = template.bodyRows[a][b].rightLineStyle; xlWorkSheet.Cells[template.bodyRows[a][b].rowIndex, template.bodyRows[a][b].columnIndex].Borders(XlBordersIndex.xlEdgeRight).Weight = template.bodyRows[a][b].rightWeight; xlWorkSheet.Cells[template.bodyRows[a][b].rowIndex, template.bodyRows[a][b].columnIndex].Borders(XlBordersIndex.xlEdgeBottom).LineStyle = template.bodyRows[a][b].bottomLineStyle; xlWorkSheet.Cells[template.bodyRows[a][b].rowIndex, template.bodyRows[a][b].columnIndex].Borders(XlBordersIndex.xlEdgeBottom).Weight = template.bodyRows[a][b].bottomWeight; xlWorkSheet.Cells[template.bodyRows[a][b].rowIndex, template.bodyRows[a][b].columnIndex].Borders(XlBordersIndex.xlEdgeLeft).LineStyle = template.bodyRows[a][b].leftLineStyle; xlWorkSheet.Cells[template.bodyRows[a][b].rowIndex, template.bodyRows[a][b].columnIndex].Borders(XlBordersIndex.xlEdgeLeft).Weight = template.bodyRows[a][b].leftWeight; } } } int c = 0; foreach (List <List <LoadTemplate.myCell> > partGroups in XML.sorted) { foreach (List <LoadTemplate.myCell> cellRows in partGroups) { foreach (LoadTemplate.myCell cell in cellRows) { writeData(cell); } } Console.WriteLine("Finished writing row: " + ++c); } Console.WriteLine("Total Part Count: " + XML.totalPartCount); xlWorkBook.SaveAs(System.AppDomain.CurrentDomain.BaseDirectory + "Ebom_testing" + getTime() + ".xlsx"); } finally { Console.WriteLine("Finished Saving Excel File"); Marshal.FinalReleaseComObject(xlWorkSheet); Marshal.FinalReleaseComObject(xlWorkSheets); xlWorkBook.Close(); Marshal.FinalReleaseComObject(xlWorkBook); xlWorkBooks.Close(); Marshal.FinalReleaseComObject(xlWorkBooks); xlApp.Quit(); Marshal.FinalReleaseComObject(xlApp); // excel objects don't releast comObjects to excel so you have to force it } }
/// <summary> /// /// </summary> /// <param name="fileName">file to get information form</param> /// <param name="sheetName">valid sheet name to get last row and column</param> /// <returns>ExcelLast</returns> public ExcelLast UsedRowsColumns(string fileName, string sheetName) { int RowsUsed = -1; int ColsUsed = -1; if (File.Exists(fileName)) { Excel.Application xlApp = null; Excel.Workbooks xlWorkBooks = null; Excel.Workbook xlWorkBook = null; Excel.Worksheet xlWorkSheet = null; Excel.Sheets xlWorkSheets = null; xlApp = new Excel.Application(); xlApp.DisplayAlerts = false; xlWorkBooks = xlApp.Workbooks; xlWorkBook = xlWorkBooks.Open(fileName); xlApp.Visible = false; xlWorkSheets = xlWorkBook.Sheets; for (int x = 1; x <= xlWorkSheets.Count; x++) { xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x]; if (xlWorkSheet.Name == sheetName) { Excel.Range xlCells = null; xlCells = xlWorkSheet.Cells; Excel.Range workRange = xlCells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell); RowsUsed = workRange.Row; ColsUsed = workRange.Column; Marshal.FinalReleaseComObject(workRange); workRange = null; Marshal.FinalReleaseComObject(xlCells); xlCells = null; break; } Marshal.FinalReleaseComObject(xlWorkSheet); xlWorkSheet = null; } xlWorkBook.Close(); xlApp.UserControl = true; xlApp.Quit(); Release(xlWorkSheets); Release(xlWorkSheet); Release(xlWorkBook); Release(xlWorkBooks); Release(xlApp); return(new ExcelLast() { Row = RowsUsed, Column = ColsUsed }); } else { throw new Exception("'" + fileName + "' not found."); } }
// 엑셀 파싱 protected override bool Internal_Excel_Parsing(ChannelGoodInfo pChannelGoodInfo) { try { if (GoodsDownInfo_.ContainsKey(pChannelGoodInfo.Goods_Code_) == false) { NewLogManager2.Instance.Log(string.Format("!! 상품 코드 엑셀이 없습니다. - {0}", pChannelGoodInfo.Goods_Code_)); return(false); } string filepath = GoodsDownInfo_[pChannelGoodInfo.Goods_Code_]; Microsoft.Office.Interop.Excel.Application ap = null; Workbook wb = null; Worksheet ws = null; HKExcelHelper.GetWorkSheet(filepath, ref ap, ref wb, ref ws); Range tRange = null; string tempString = ""; string comparesitename = ""; Int32 nCurrentRow = LQCrawlerInfo_.ExData_Start_; Int32 ExData_Option = LQCrawlerInfo_.ExData_Option_; Int32 ExData_Coupncode = LQCrawlerInfo_.ExData_Coupncode_; Int32 ExData_Buyer = LQCrawlerInfo_.ExData_Buyer_; Int32 ExData_Cancel = LQCrawlerInfo_.ExData_Cancel_; Int32 ExData_Use = LQCrawlerInfo_.ExData_Use_; Int32 ExData_Buyphone = LQCrawlerInfo_.ExData_Buyphone_; Int32 ExData_Price = LQCrawlerInfo_.ExData_Price_; Int32 ExData_BuyDate = LQCrawlerInfo_.ExData_Buydate_; Int32 ExData_BuyCount = LQCrawlerInfo_.ExData_Count_; Int32 ExData_GoodsName = LQCrawlerInfo_.ExData_GoodName_; Int32 ExData_BasicColumn = 22; if (nCurrentRow > 0) { ProcessStateManager.Instance.NeedParsingCount_ += (ws.UsedRange.Rows.Count - (nCurrentRow - 1)); } while (true) { try { tRange = ws.Cells[nCurrentRow, 1]; comparesitename = Convert.ToString(tRange.Value2); tRange = ws.Cells[nCurrentRow, ExData_Option]; if (tRange == null) { break; } tempString = tRange.Value2; tRange = ws.Cells[nCurrentRow, ExData_BasicColumn]; string State = Convert.ToString(tRange.Value2); if (State == "완료취소") { nCurrentRow++; continue; } Int32 tempgoodSeq = -1; COrderData pExcelData = new COrderData(); pExcelData.channelSeq_ = LQCrawlerInfo_.Channel_Idx_; pExcelData.authoritySeq_ = LQCrawlerInfo_.AuthoritySeq_; pExcelData.goodsSeq_ = tempgoodSeq; pExcelData.ExData_Option_ = tempString; pExcelData.ExData_OptionOriginal_ = tempString; tRange = ws.Cells[nCurrentRow, ExData_GoodsName]; pExcelData.ExData_GoodsName_ = tRange.Value2; pExcelData.ExData_GoodsNick_ = Regex.Replace(pExcelData.ExData_GoodsName_, @"[^a-zA-Z0-9가-힣]", ""); tRange = ws.Cells[nCurrentRow, ExData_Coupncode]; if (tRange == null) { break; } pExcelData.channelOrderCode_ = Convert.ToString(tRange.Value2); if (pExcelData.channelOrderCode_ == null) { break; } pExcelData.channelOrderCode_ = pExcelData.channelOrderCode_.Replace("'", ""); pExcelData.channelOrderCode_ = pExcelData.channelOrderCode_.Trim(); // 공백 제거 tRange = ws.Cells[nCurrentRow, ExData_Buyer]; pExcelData.orderName_ = Convert.ToString(tRange.Value2); if (pExcelData.orderName_ == null) { pExcelData.orderName_ = ""; } tRange = ws.Cells[nCurrentRow, ExData_Cancel]; pExcelData.ExData_Cancel_ = tRange.Value2; if (pExcelData.ExData_Cancel_ == null) { pExcelData.ExData_Cancel_ = ""; } tRange = ws.Cells[nCurrentRow, ExData_Use]; pExcelData.ExData_Use_ = tRange.Value2; if (pExcelData.ExData_Use_ == null) { pExcelData.ExData_Use_ = ""; } tRange = ws.Cells[nCurrentRow, ExData_Buyphone]; pExcelData.orderPhone_ = Convert.ToString(tRange.Value2); if (pExcelData.orderPhone_ == null) { pExcelData.orderPhone_ = ""; } pExcelData.orderPhone_ = pExcelData.orderPhone_.Replace("'", ""); if (ExData_Price != 0) { tRange = ws.Cells[nCurrentRow, ExData_Price]; if (tRange.Value2 != null) { // 돈에 , 가 있으면 제거하자. tempString = Convert.ToString(tRange.Value2); tempString = tempString.Replace(",", ""); pExcelData.orderSettlePrice_ = Convert.ToInt32(tempString); } } tRange = ws.Cells[nCurrentRow, ExData_BuyDate]; double temp = Convert.ToDouble(tRange.Value2); DateTime dta = DateTime.FromOADate(temp); pExcelData.BuyDate_ = dta.ToString("u"); pExcelData.BuyDate_ = pExcelData.BuyDate_.Replace("Z", ""); if (ExData_BuyCount != 0)// 구매갯수를 따로 뽑아야 하는 채널에서만 { tRange = ws.Cells[nCurrentRow, ExData_BuyCount]; pExcelData.BuyCount_ = Convert.ToInt32(tRange.Value2); } SplitDealAndInsertExcelData(pExcelData, comparesitename); } catch (System.Exception ex) { NewLogManager2.Instance.Log(string.Format("엑셀 파싱 에러 : {0}", ex.Message)); break; //nCurrentRow++; //continue; } ProcessStateManager.Instance.CurParsingCount_++; nCurrentRow++; } wb.Close(false, Type.Missing, Type.Missing); ap.Quit(); Marshal.FinalReleaseComObject(ws); Marshal.FinalReleaseComObject(wb); Marshal.FinalReleaseComObject(ap); ws = null; wb = null; ap = null; GC.Collect(); } catch (System.Exception ex) { NewLogManager2.Instance.Log(string.Format("Error public override bool Internal_Excel_Parsing - {0}", ex.Message)); return(false); } return(true); }
/// <summary> /// Get last used column for a row /// </summary> /// <param name="fileName"></param> /// <param name="sheetName"></param> /// <param name="row"></param> /// <returns></returns> public int LastColumnForRow(string fileName, string sheetName, int row) { int lastColumn = -1; if (File.Exists(fileName)) { Excel.Application xlApp = null; Excel.Workbooks xlWorkBooks = null; Excel.Workbook xlWorkBook = null; Excel.Worksheet xlWorkSheet = null; Excel.Sheets xlWorkSheets = null; xlApp = new Excel.Application(); xlApp.DisplayAlerts = false; xlWorkBooks = xlApp.Workbooks; xlWorkBook = xlWorkBooks.Open(fileName); xlApp.Visible = false; xlWorkSheets = xlWorkBook.Sheets; for (int x = 1; x <= xlWorkSheets.Count; x++) { xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x]; if (xlWorkSheet.Name == sheetName) { Excel.Range xlCells = null; xlCells = xlWorkSheet.Cells; Excel.Range workRange = xlCells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell); Excel.Range xlColumns = xlWorkSheet.Columns; int count = xlColumns.Count; Marshal.FinalReleaseComObject(xlColumns); xlColumns = null; Excel.Range xlLastRange = (Excel.Range)xlWorkSheet.Cells[row, count]; Excel.Range xlDirRange = xlLastRange.End[Excel.XlDirection.xlToLeft]; Marshal.FinalReleaseComObject(xlLastRange); xlLastRange = null; lastColumn = xlDirRange.Column; Marshal.FinalReleaseComObject(xlDirRange); xlDirRange = null; Marshal.FinalReleaseComObject(workRange); workRange = null; Marshal.FinalReleaseComObject(xlCells); xlCells = null; break; } Marshal.FinalReleaseComObject(xlWorkSheet); xlWorkSheet = null; } xlWorkBook.Close(); xlApp.UserControl = true; xlApp.Quit(); Release(xlWorkSheets); Release(xlWorkSheet); Release(xlWorkBook); Release(xlWorkBooks); Release(xlApp); return(lastColumn); } else { throw new Exception("'" + fileName + "' not found."); } }
public void Initialize(IPluginSettings Settings) => Marshal.FinalReleaseComObject(Settings);
/// <summary> /// 刻录 /// </summary> public void Burn(string diskName = "SinoUnion") { if (!CanBurn) { throw new Exception("当前磁盘状态不支持刻录"); } if (string.IsNullOrEmpty(diskName)) { throw new Exception("DiskName不能为空"); } if (BurnMediaList.Count <= 0) { throw new Exception("待刻录文件列表不能为空"); } if (BurnMediaFileSize <= 0) { throw new Exception("待刻录文件大小为0"); } try { //说明 //1.fsi.ChooseImageDefaults用的是IMAPI2FS的,我们定义的msRecorder是IMAPI2的.所以必须用动态类型 //2.dataWriter也要使用动态类型,要不然Update事件会出异常. // Create an image stream for a specified directory. dynamic fsi = new IMAPI2FS.MsftFileSystemImage(); // Disc file system IMAPI2FS.IFsiDirectoryItem dir = fsi.Root; // Root directory of the disc file system dynamic dataWriter = new MsftDiscFormat2Data(); //Create the new disc format and set the recorder dataWriter.Recorder = msRecorder; dataWriter.ClientName = "SinoGram"; //不知道这方法不用行不行.用的参数是IMAPI2FS的. //所以学官网的例子,把fsi改成了动态的.使用msRecorder作为参数 fsi.ChooseImageDefaults(msRecorder); //设置相关信息 fsi.VolumeName = diskName; //刻录磁盘名称 for (int i = 0; i < BurnMediaList.Count; i++) { dir.AddTree(BurnMediaList[i].MediaPath, true); } // Create an image from the file system IStream stream = fsi.CreateResultImage().ImageStream; try { dataWriter.Update += new DDiscFormat2DataEvents_UpdateEventHandler(BurnProgressChanged); dataWriter.Write(stream);// Write stream to disc } catch (System.Exception ex) { throw ex; } finally { if (stream != null) { Marshal.FinalReleaseComObject(stream); } } } catch (Exception ex) { Console.WriteLine($"刻录失败:{ex.Message}"); } }
private void CreateFSIFile(FileInfo file, IFsiDirectoryItem diritem) { var realpath = UniqueListFileSystemInfo.GetPhysicalPath(file.FullName); var index = realpath.IndexOf(":\\") + 1; if (_sysImage.Exists(realpath.Substring(index)) == FsiItemType.FsiItemNotFound) { var crtdiritem = diritem; var name = Path.GetFileName(realpath); if (string.Compare(diritem.FullPath, Path.GetDirectoryName(realpath).Substring(index), true) != 0) { var fsipath = Path.GetDirectoryName(realpath).Substring(index + 1 + diritem.FullPath.Length); var dirs = fsipath.Split('\\'); var dInfo = new DirectoryInfo(CaptureDirectory); var subdirs = dInfo.FullName.Split('\\'); //MessageBox.Show(subdirs.Length.ToString()); //create the subdirs one by one foreach (var dir in dirs.Skip(subdirs.Length - 1)) { if (dir.Length == 0) { continue; //in the root like C:\ } try { var newpath = string.Format("{0}\\{1}", crtdiritem.FullPath, dir); if (_sysImage.Exists(newpath) != FsiItemType.FsiItemDirectory) { crtdiritem.AddDirectory(dir); } } catch { Cancel = true; throw; } crtdiritem = crtdiritem[dir] as IFsiDirectoryItem; } } COMTypes.IStream newStream = null; try { newStream = LoadCOMStream(realpath); crtdiritem.AddFile(name, newStream); } finally { Marshal.FinalReleaseComObject(newStream); } ActualSize += file.Length; if (Update != null && Update.GetInvocationList().Length > 0) { Update(file.FullName, file.Length); } } else { throw new ApplicationException(realpath.Substring(index) + " occurs in multiple source folders with the same name."); } }
private void SaveSettings() { using (var ms = new MemoryStream()) { var bf = new BinaryFormatter(); bf.Serialize(ms, _tempApplicationData.Bookmarks); ms.Position = 0; var buffer = new byte[(int)ms.Length]; ms.Read(buffer, 0, buffer.Length); Properties.Settings.Default.SavedBookmarks = Convert.ToBase64String(buffer); } Properties.Settings.Default.Save(); const string shortcutName = "VagrantTray.lnk"; var startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); var startupShortcut = Path.Combine(startupPath, shortcutName); if (Properties.Settings.Default.LaunchOnWindowsStartup) { if (!File.Exists(startupShortcut)) { var t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object dynamic shell = Activator.CreateInstance(t); try { var lnk = shell.CreateShortcut(startupShortcut); try { lnk.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location; lnk.IconLocation = "shell32.dll, 1"; lnk.Save(); } finally { Marshal.FinalReleaseComObject(lnk); } } finally { Marshal.FinalReleaseComObject(shell); } } } else if (File.Exists(startupShortcut)) { File.Delete(startupShortcut); } var newBookmarks = _tempApplicationData.Bookmarks.Where( b => !_applicationData.Bookmarks.Contains(b, new BookmarkEqualityComparer())).ToList(); var removedBookmarks = _applicationData.Bookmarks.Where( b => !_tempApplicationData.Bookmarks.Contains(b, new BookmarkEqualityComparer())).ToList(); foreach (var removedBookmark in removedBookmarks) { _applicationData.Bookmarks.Remove(removedBookmark); } foreach (var newBookmark in newBookmarks) { _applicationData.Bookmarks.Add(newBookmark); } }
private static Encoding DetectOutgoingEncoding(string input, int[] preferedEncodings, bool preserveOrder) { if (input == null) { throw new ArgumentNullException("input"); } // empty strings can always be encoded as ASCII if (input.Length == 0) { return(Encoding.ASCII); } Encoding result = Encoding.ASCII; // get the IMultiLanguage3 interface MultiLanguage.IMultiLanguage3 multilang3 = new MultiLanguage.CMultiLanguageClass(); if (multilang3 == null) { throw new System.Runtime.InteropServices.COMException("Failed to get IMultilang3"); } try { int[] resultCodePages = new int[preferedEncodings != null ? preferedEncodings.Length : Encoding.GetEncodings().Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = preferedEncodings == null ? IntPtr.Zero : Marshal.AllocCoTaskMem(sizeof(uint) * preferedEncodings.Length); IntPtr pDetectedEncs = Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (preferedEncodings != null) { Marshal.Copy(preferedEncodings, 0, pPrefEncs, preferedEncodings.Length); } Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MultiLanguage.MLCPF options = MultiLanguage.MLCPF.MLDETECTF_VALID_NLS; if (preserveOrder) { options |= MultiLanguage.MLCPF.MLDETECTF_PRESERVE_ORDER; } if (preferedEncodings != null) { options |= MultiLanguage.MLCPF.MLDETECTF_PREFERRED_ONLY; } MultiLanguage.HRESULT hres; hres = multilang3.DetectOutboundCodePage( options, input, (uint)input.Length, pPrefEncs, (uint)(preferedEncodings == null ? 0 : preferedEncodings.Length), pDetectedEncs, ref detectedCodepages, ref specialChar); if (hres != MultiLanguage.HRESULT.S_OK) { MessageBox.Show("Error 1 ! HRESULT=" + hres.ToString()); } // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); result = Encoding.GetEncoding(theResult[0]); } } finally { if (pPrefEncs != IntPtr.Zero) { Marshal.FreeCoTaskMem(pPrefEncs); } Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } return(result); }
static void loadExcel(string file, int startrow, int endrow) { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Visible = true; excel.Visible = false; Excel.Workbook theWorkbook; Excel.Worksheet worksheet; theWorkbook = excel.Workbooks.Open(file, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); worksheet = theWorkbook.Worksheets[1]; Excel.Range range; int succeeded = 0; int failed = 0; for (int row = startrow; row <= endrow; row++) { GeoPoint locPoint = new GeoPoint(); string cellName; //check if there is already a house has the same code name if so skip it cellName = "A" + row.ToString(); range = worksheet.get_Range(cellName, Missing.Value); string codeName = range.Value2.ToString(); var tId = Guid.Empty; if (houseService.HouseExistByCodeName(codeName)) { tId = houseService.FindHouseByCodeName(codeName).Id; Console.WriteLine("house exists"); } //check if it has a name if not skip if cellName = "B" + row.ToString(); range = worksheet.get_Range(cellName, Missing.Value); string houseName = range.Value2.ToString(); if (string.IsNullOrEmpty(houseName)) { Console.WriteLine("no house name, skip"); failed++; continue; } //chekck if the location is validte if not skip cellName = "C" + row.ToString(); string location = worksheet.get_Range(cellName, Missing.Value).Value2.ToString(); try { locPoint = HouseService.GetGeoPoint(location); } catch { failed++; Console.WriteLine("invalid location, skip"); continue; } //all check noe build a house //user the code name to locate the photo folder var path = file.Substring(0, file.LastIndexOf(@"\") + 1) + @"photo\" + codeName; var photos = new List <string>(); try { photos = getPhotos(path, codeName).ToList <string>(); } catch { Console.WriteLine("no photo"); } DateTime year = DateTime.Parse("0001 06 06"); try { year = DateTime.Parse(worksheet.get_Range("I" + row.ToString(), Missing.Value).Value2.ToString() + " 06 01"); } catch { //no build year } House newHouse = new House { CodeName = codeName, Name = houseName, Images = photos.Any() ? photos : null, Cover = photos.Any() ? photos[0] : null, Location = locPoint, LocationString = worksheet.get_Range("D" + row.ToString(), Missing.Value).Value2.ToString(), Abstarct = worksheet.get_Range("E" + row.ToString(), Missing.Value).Value2.ToString(), Country = worksheet.get_Range("F" + row.ToString(), Missing.Value).Value2.ToString(), Province = worksheet.get_Range("G" + row.ToString(), Missing.Value).Value2.ToString(), City = worksheet.get_Range("H" + row.ToString(), Missing.Value).Value2.ToString(), //BuiltYear = year, //Condition = worksheet.get_Range("K" + row.ToString(), Missing.Value).Value2.ToString(), //historica , photo value is not fixed yet Description = worksheet.get_Range("P" + row.ToString(), Missing.Value).Value2.ToString(), }; newHouse.AddExtraInformation("houseinfo-condition", worksheet.get_Range("K" + row.ToString(), Missing.Value).Value2.ToString()); newHouse.AddExtraInformation("houseinfo-buildyear", year.Year); string tagString; try { tagString = worksheet.get_Range("L" + row.ToString(), Missing.Value).Value2.ToString(); newHouse.Tags = tagString.Split(';').ToList <string>(); } catch (Exception) { newHouse.Tags = null; } var extra = worksheet.get_Range("Q" + row.ToString(), Missing.Value).Value2; if (extra != null) { string extraStr = extra.ToString(); getExtra(extraStr, newHouse); } if (tId == Guid.Empty) { houseService.InsertOne(newHouse); succeeded++; Console.WriteLine("house added: " + codeName); } else { newHouse.Id = tId; houseService.SaveOne(newHouse); succeeded++; Console.WriteLine("house updated: " + codeName); } } //clean up theWorkbook.Close(false, Type.Missing, Type.Missing); Marshal.ReleaseComObject(theWorkbook); excel.Quit(); Marshal.FinalReleaseComObject(excel); Console.WriteLine("succeeded:" + succeeded); Console.WriteLine("failed:" + failed); }