internal SelectForm(string[] items, string title, bool multi, Image[] previews, string[] tooltips) { InitializeComponent(); this.Icon = Fomm.Properties.Resources.fomm02; Properties.Settings.Default.windowPositions.GetWindowPosition("PackageManagerSelectForm", this); Text = title; toolTips = tooltips; Multi = multi; System.Collections.Generic.List<int> selected = new System.Collections.Generic.List<int>(); for (int i = 0; i < items.Length; i++) { if (items[i].Length == 0) continue; if (items[i][0] == '|') { items[i] = items[i].Substring(1); selected.Add(i); if (!Multi) break; } } lbSelect.Items.AddRange(items); if (Multi) { lbSelect.SelectionMode = SelectionMode.MultiExtended; label1.Text = "Select any number of options (Use ctrl and shift for multiselect)"; if (selected.Count > 0) foreach (int i in selected) lbSelect.SetSelected(i, true); } else { if (selected.Count == 0) lbSelect.SelectedIndex = 0; else lbSelect.SelectedIndex = selected[0]; } if (toolTips == null) bDescription.Visible = false; if (previews != null) Previews = previews; else bPreview.Visible = false; lbSelect_SelectedIndexChanged(null, null); }
public int addItem(int appNumber) { getFiles(appNumber); getIcon(appNumber); pictureBox2 = new System.Windows.Forms.PictureBox[files.Length]; flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel[files.Length]; label = new System.Windows.Forms.Label[fileNames.Length]; flow = System.Windows.Forms.FlowDirection.TopDown; img = (System.Drawing.Image)bitmap; for (int i = 0; i < files.Length; i++) { flowLayoutPanel2[i] = new System.Windows.Forms.FlowLayoutPanel(); flowLayoutPanel2[i].AutoSize = false; flowLayoutPanel2[i].FlowDirection = flow; pictureBox2[i] = new System.Windows.Forms.PictureBox(); pictureBox2[i].Image = img; pictureBox2[i].Size = size; pictureBox2[i].Parent = this.flowLayoutPanel2[i]; this.flowLayoutPanel2[i].Size = size; label[i] = new System.Windows.Forms.Label(); label[i].ForeColor = System.Drawing.Color.White; label[i].Text = fileNames[i]; label[i].AutoSize = true; label[i].Parent = this.flowLayoutPanel2[i]; this.flowLayoutPanel2[i].Parent = this.flowLayoutPanel1; } return files.Length; }//end of addItem
public void Load(Image img) { var shouldUseCompression = false; Dispatcher.Invoke(new Action(() => shouldUseCompression = _main.UseCompression.IsChecked)); _assetFile.SetBackground(img, shouldUseCompression); Dispatcher.Invoke(new Action(() => SetPreview(img))); }
public FileItem(string path) { if (!File.Exists(path)) { throw new FileNotFoundException("The file added to FileItem was not found!", path); } filePath = path; var fileInfo = new FileInfo(filePath); displayName = fileInfo.Name; m_fileLength = fileInfo.Length; // Get the File icon var shinfo = new SHFILEINFO(); IntPtr hImg = NativeMethods.SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_SMALLICON); //The icon is returned in the hIcon member of the shinfo struct var imageConverter = new System.Drawing.IconConverter(); var icon = System.Drawing.Icon.FromHandle(shinfo.hIcon); try { fileIconImage = (System.Drawing.Image) imageConverter.ConvertTo(icon, typeof(System.Drawing.Image)); } catch (NotSupportedException) { } NativeMethods.DestroyIcon(shinfo.hIcon); }
void Initialize() { icon = null; samplesPerSecond = Settings.Instance.GetInt( "/Settings/Output/Sound/General/SamplesPerSecond"); posIncrement = Math.PI * 2.0 / (double) samplesPerSecond; }
public DayWeather(short high, short low, string condition, System.Drawing.Image icon) { Icon = icon; this.High = high; this.Low = low; this.Condition = condition; }
public Monster(string name, WarriorStats stats, int xpreward, int goldreward, System.Drawing.Image picture) { this.Name = name; this.stats = stats; this.xpreward = xpreward; this.goldreward = goldreward; this.picture = picture; }
public TodayWeather(short tempC, short tempF, String condition, String humidity, String wind, System.Drawing.Image icon) { this.Icon = icon; this.TempC = tempC; this.TempF = tempF; this.Wind = wind; this.Humidity = humidity; this.Condition = condition; }
byte[] ImageToByteArray(Image image) { if (image == null) { throw new ArgumentNullException("image"); } using (var ms = new MemoryStream()) { image.Save(ms, image.RawFormat); return ms.ToArray(); } }
public PictureFrame(System.Drawing.Image image, string description, PictureType pictureType) : this(description, pictureType) { if(image==null) { throw new ArgumentNullException("The passed image object can not be null."); } this._image=image; }
public Item(SerializationInfo info, StreamingContext ctxt) { this.id = (int)info.GetValue("id", typeof(int)); this.name = (string)info.GetValue("name", typeof(string)); this.value = (int)info.GetValue("value", typeof(int)); this.weight = (int)info.GetValue("weight", typeof(int)); this.type = (ItemType)info.GetValue("type", typeof(int)); this.picture = (System.Drawing.Image)info.GetValue("picture", typeof(System.Drawing.Image)); }
public BOXuliMayIn(Transit transit) { mTransit = transit; mKaraokeEntities = new KaraokeEntities(); _CAIDATMAYINBEP = BOCaiDatMayInBep.GetQueryNoTracking(mKaraokeEntities); _CAIDATMAYINHOADON = BOCaiDatMayInHoaDon.GetQueryNoTracking(mKaraokeEntities); _ImageLogo = Utilities.ImageHandler.BitmapImage2Bitmap(this._CAIDATMAYINHOADON.Logo); }
private void button1_Click(object sender, EventArgs e) { openFileDialog1.Filter = "Image files (*.jpg;*.jpeg;*.bmp;*.gif;*.gif)|*.jpg;*.jpeg;*.bmp;*.gif;*.gif|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { backgroundImage = new System.Drawing.Bitmap(openFileDialog1.FileName); textBox1.Text = openFileDialog1.FileName; pictureBox1.BackgroundImage = backgroundImage; } }
public void Load(Image img, bool icon) { var shouldUseCompression = false; Dispatcher.Invoke(new Action(() => shouldUseCompression = _main.UseCompression.IsChecked)); if(icon) _assetFile.SetIcon(img, shouldUseCompression); else _assetFile.SetBanner(img, shouldUseCompression); Dispatcher.Invoke(new Action(() => SetPreview(img, icon))); }
/// <summary> /// /// </summary> /// <param name="directoryPath"></param> public DirectoryItem(string directoryPath) { if (Directory.Exists(directoryPath)) { //throw new FileNotFoundException("The directory added to DirectoryItem was not found!", directoryPath); m_directoryPath = directoryPath; FileInfo fileInfo = new FileInfo(m_directoryPath); displayName = fileInfo.Name; // // Get all the files in the directory // string[] files = Directory.GetFiles(m_directoryPath); foreach (string file in files) { mediaItems.Add(new FileItem(file)); } // // Get all the subdirectories // string[] directories = Directory.GetDirectories(m_directoryPath); foreach (string directory in directories) { mediaItems.Add(new DirectoryItem(directory)); } // // Get the Directory icon // SHFILEINFO shinfo = new SHFILEINFO(); IntPtr hImg = Win32.SHGetFileInfo(m_directoryPath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON); if (shinfo.hIcon != null) { //The icon is returned in the hIcon member of the shinfo struct System.Drawing.IconConverter imageConverter = new System.Drawing.IconConverter(); System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(shinfo.hIcon); try { fileIconImage = (System.Drawing.Image) imageConverter.ConvertTo(icon, typeof(System.Drawing.Image)); } catch (NotSupportedException) { } Win32.DestroyIcon(shinfo.hIcon); } } }
public Monster(int monsterid) { this.name = MonsterStats.GetStat(monsterid, "name"); this.level = int.Parse(MonsterStats.GetStat(monsterid, "level")); this.hp = this.maxhp = int.Parse(MonsterStats.GetStat(monsterid, "hp")); this.xpreward = int.Parse(MonsterStats.GetStat(monsterid, "xp")); this.goldreward = int.Parse(MonsterStats.GetStat(monsterid, "gold")); this.accuracy = int.Parse(MonsterStats.GetStat(monsterid, "accuracy")); this.strength = int.Parse(MonsterStats.GetStat(monsterid, "damage")); this.speed = int.Parse(MonsterStats.GetStat(monsterid, "speed")); this.picture = SimpleGame.Properties.Resources.rabbit_image; }
public IDCard(string connectionString, string dataSourceType, string tableName,string primaryKey, string extraTableName, System.Drawing.Size dimensions, System.Drawing.Image backgroundImage, ArrayList fields, ArrayList selectedFields,String title) { this.extraTableName = extraTableName; this.primaryKey = primaryKey; this.dataSourceType = dataSourceType; this.title = title; this.connectionString = connectionString; this.tableName = tableName; this.dimensions = dimensions; this.backgroundImage = backgroundImage; this.fields = fields; this.selectedFields = selectedFields; }
public static void SplitTiff(string fileName) { System.Drawing.Image imageFile = System.Drawing.Image.FromFile(fileName); System.Drawing.Imaging.FrameDimension frameDimensions = new System.Drawing.Imaging.FrameDimension(imageFile.FrameDimensionsList[0]); int numberOfImages = imageFile.GetFrameCount(frameDimensions); System.Drawing.Image[] img = new System.Drawing.Image[numberOfImages]; for (int intFrame = 0; intFrame < numberOfImages; intFrame++) { imageFile.SelectActiveFrame(frameDimensions, intFrame); img[intFrame] = imageFile; } img[0].Save(@"C:\YpiiData\test55.tif"); }
public ModData(string name, string path, bool iszip=false) { this.Name = StripSpecialChars(name); this.Path = path; this.IsZip = iszip; this.Enabled = false; this.SortValue = 9999; //New mods are sorted at bottom of list this.Text = ""; this.Image = null; LoadModInfo(); }
//***Constructor that takes 8 arguments to assign all properties for Expense Item object. public ExpenseItem (string date1, string description1, string miles1, string expenseType1, string expenseCode1, string rate1, string totalExpense1, string mileageTotal1, System.Drawing.Image receiptImage1) { date = date1; description = description1; miles = miles1; expenseType = expenseType1; expenseCode = expenseCode1; rate = rate1; totalExpense = totalExpense1; mileageTotal = mileageTotal1; receiptImage = receiptImage1; }
public void PushCursorUpdate(byte[] data) { if (data != null) { // Unpack the data. // Utils.UnpackCursorCaptureData(data, out _cursor, out _cursorX, out _cursorY); } else { _cursor = null; } }
public static byte[] ConvertImageToByteArray(Image imageToConvert, ImageFormat formatOfImage) { if (imageToConvert == null) { return null; } using (MemoryStream ms = new MemoryStream()) { imageToConvert.Save(ms, formatOfImage); return ms.ToArray(); } }
private void VerificationFailed(string message = "", Image image = null) { if (message == "") message = GetErrorMessage(); if (failTest) { Assert.Fail(message); } else { if (image == null) TestBase.AddVerificationError(message); else TestBase.AddVerificationError(message, image); } }
/// <summary> /// Creates a new ElementControl that can create clones of el. /// </summary> /// <param name="el">Element that should be cloned.</param> /// <param name="label">Label for the element.</param> /// <param name="font">Font used for the label.</param> public ElementControl(PinballElement el, string label, Font font) { InitializeComponent(); // Assign instance vars ElementFont = font; Element = el; Label = label; Height = THUMB_HEIGHT; Width = 200; // Add event listeners MouseEnter += (s, e) => { BackColor = System.Drawing.SystemColors.Highlight; ForeColor = Color.White; }; MouseLeave += (s, e) => { BackColor = System.Drawing.SystemColors.Control; ForeColor = Color.Black; }; thumb = GetImage(); }
public TestCustomRenderSettings(RenderSettings renderSettings, string fieldName, float maxValue) { this.maxValue = maxValue; this.renderSettings = renderSettings; this.fieldName = fieldName; string[] fieldNames = renderSettings.DbfReader.GetFieldNames(); int index = fieldNames.Length-1; while (index >= 0) { if (string.Compare(fieldNames[index].Trim(), fieldName, StringComparison.OrdinalIgnoreCase) == 0) { break; } index--; } fieldIndex = index; customImage = CreateCustomImage(renderSettings.GetImageSymbol()); }
public override void Refresh() { base.Refresh(); using (RenderTarget2D target = new RenderTarget2D(device, Bounds.Width, Bounds.Height)) { SpriteBatch sb = new SpriteBatch(device); device.SetRenderTarget(target); device.Clear(Color.Transparent); sb.Begin(); Draw(sb); sb.End(); device.SetRenderTarget(null); image = ToDColorBmp(target.GetColorData(), Bounds.Width, Bounds.Height); } }
public ImageHandler(string name, Stream stream) { _filename = name; original_image = System.Drawing.Image.FromStream(stream); _final_image = new System.Drawing.Bitmap(stream); _currentType = name.Substring(name.LastIndexOf('.')).ToLower(); switch (_currentType) { case ".jpg": case ".jpeg": _format = System.Drawing.Imaging.ImageFormat.Jpeg; break; case ".bmp": _format = System.Drawing.Imaging.ImageFormat.Bmp; break; case ".png": _format = System.Drawing.Imaging.ImageFormat.Png; break; case ".gif": _format = System.Drawing.Imaging.ImageFormat.Gif; break; } }
public DirectoryItem(string directoryPath) { if (!Directory.Exists(directoryPath)) { throw new FileNotFoundException("The directory added to DirectoryItem was not found!", directoryPath); } m_directoryPath = directoryPath; var fileInfo = new FileInfo(m_directoryPath); DisplayName = fileInfo.Name; string[] files = Directory.GetFiles(m_directoryPath); foreach (string file in files) mediaItems.Add(new FileItem(file)); string[] directories = Directory.GetDirectories(m_directoryPath); foreach (string directory in directories) mediaItems.Add(new DirectoryItem(directory)); var shinfo = new SHFILEINFO(); IntPtr hImg = NativeMethods.SHGetFileInfo(m_directoryPath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_SMALLICON); //The icon is returned in the hIcon member of the shinfo struct var imageConverter = new System.Drawing.IconConverter(); var icon = System.Drawing.Icon.FromHandle(shinfo.hIcon); try { fileIconImage = (System.Drawing.Image) imageConverter.ConvertTo(icon, typeof(System.Drawing.Image)); } catch (NotSupportedException) { } NativeMethods.DestroyIcon(shinfo.hIcon); }
protected override void Decode(byte[] content) { int offset = 1; int read; Price = ID3Utils.ReadString(content, offset, -1, ID3Utils.Iso88591, out read); offset += read; IsValidUntil = ID3Utils.ReadString(content, offset, -1, ID3Utils.Iso88591, out read); offset += read; ContactURL = ID3Utils.ReadString(content, offset, -1, ID3Utils.Iso88591, out read); offset += read; ReceivedType = (ReceivedType)content[offset]; offset++; var encoding = ID3Utils.GetEncoding(content, 0, offset); offset++; SellerName = ID3Utils.ReadString(content, offset, -1, encoding, out read); offset += read; Description = ID3Utils.ReadString(content, offset, -1, encoding, out read); offset += read; if (offset < content.Length) { //we've got a attached logo LogoMimeType = ID3Utils.ReadString(content, offset, -1, ID3Utils.Iso88591, out read); offset += read; var logoData = new byte[content.Length - offset]; Array.Copy(content, offset, logoData, 0, logoData.Length); Image = ID3Utils.DecodeImage(logoData, LogoMimeType); } }
public virtual TextCompletionItem AddTextItem(string completionTextString, System.Drawing.Image picture) { return(Completion.AddTextCompletionItem(completionTextString, picture)); }
/// <summary> /// Get folder information /// </summary> /// <param name="path"></param> /// <returns></returns> private string GetFolderInfo(string path) { if (!IsInRootPath(path)) { return(Error("Attempt to view files outside root path")); } if (!Directory.Exists(Server.MapPath(path))) { return(Error("Directory not found")); } DirectoryInfo RootDirInfo = new DirectoryInfo(Server.MapPath(path)); StringBuilder sb = new StringBuilder(); sb.AppendLine("{"); int i = 0; foreach (DirectoryInfo DirInfo in RootDirInfo.GetDirectories()) { if (i > 0) { sb.Append(","); sb.AppendLine(); } sb.AppendLine("\"" + Path.Combine(path, DirInfo.Name) + "\": {"); sb.AppendLine("\"Path\": \"" + Path.Combine(path, DirInfo.Name) + "/\","); sb.AppendLine("\"Filename\": \"" + DirInfo.Name + "\","); sb.AppendLine("\"File Type\": \"dir\","); sb.AppendLine("\"Preview\": \"" + IconDirectory + "_Open.png\","); sb.AppendLine("\"Properties\": {"); sb.AppendLine("\"Date Created\": \"" + DirInfo.CreationTime.ToString() + "\", "); sb.AppendLine("\"Date Modified\": \"" + DirInfo.LastWriteTime.ToString() + "\", "); sb.AppendLine("\"Height\": 0,"); sb.AppendLine("\"Width\": 0,"); sb.AppendLine("\"Size\": 0 "); sb.AppendLine("},"); sb.AppendLine("\"Error\": \"\","); sb.AppendLine("\"Code\": 0 "); sb.Append("}"); i++; } foreach (FileInfo fileInfo in RootDirInfo.GetFiles()) { if (i > 0) { sb.Append(","); sb.AppendLine(); } sb.AppendLine("\"" + Path.Combine(path, fileInfo.Name) + "\": {"); sb.AppendLine("\"Path\": \"" + Path.Combine(path, fileInfo.Name) + "\","); sb.AppendLine("\"Filename\": \"" + fileInfo.Name + "\","); sb.AppendLine("\"File Type\": \"" + fileInfo.Extension.Replace(".", "") + "\","); if (IsImage(fileInfo)) { sb.AppendLine("\"Preview\": \"" + Path.Combine(path, fileInfo.Name) + "\","); } else { var icon = String.Format("{0}{1}.png", IconDirectory, fileInfo.Extension.Replace(".", "")); if (!System.IO.File.Exists(Server.MapPath(icon))) { icon = String.Format("{0}default.png", IconDirectory); } sb.AppendLine("\"Preview\": \"" + icon + "\","); } sb.AppendLine("\"Properties\": {"); sb.AppendLine("\"Date Created\": \"" + fileInfo.CreationTime.ToString() + "\", "); sb.AppendLine("\"Date Modified\": \"" + fileInfo.LastWriteTime.ToString() + "\", "); if (IsImage(fileInfo)) { using (System.Drawing.Image img = System.Drawing.Image.FromFile(fileInfo.FullName)) { sb.AppendLine("\"Height\": " + img.Height.ToString() + ","); sb.AppendLine("\"Width\": " + img.Width.ToString() + ","); } } sb.AppendLine("\"Size\": " + fileInfo.Length.ToString() + " "); sb.AppendLine("},"); sb.AppendLine("\"Error\": \"\","); sb.AppendLine("\"Code\": 0 "); sb.Append("}"); i++; } sb.AppendLine(); sb.AppendLine("}"); return(sb.ToString()); }
private void Application_Startup(object sender, StartupEventArgs e) { try { // create helpers iHelper = new Helper(e.Args); ICrashLogDumper d = new CrashLogDumperWindow(ResourceManager.Icon, iHelper.Title, iHelper.Product, iHelper.Version); iHelper.AddCrashLogDumper(d); iHelperAutoUpdate = new HelperAutoUpdate(iHelper, new Linn.Toolkit.Wpf.ViewAutoUpdateStandard(ResourceManager.IconSongcaster, Linn.Songcast.Properties.Resources.IconLarge), new Invoker(this.Dispatcher)); iHelperAutoUpdate.Start(); // create the model iModel = new Model(new Invoker(this.Dispatcher), iHelper); iHelper.ProcessOptionsFileAndCommandLine(); // this should be created before PreferencesWindowClosing event can be called or PreferencesWindowClosing will raise a null reference exception iWaitMainWindowClosed = new AutoResetEvent(false); // create the preferences window and controller iPreferencesWindow = new PreferencesWindow(iHelper, new PreferenceBindings(iModel, iHelperAutoUpdate.OptionPageUpdates), iModel, iHelperAutoUpdate); iPreferencesWindow.Closing += PreferencesWindowClosing; iPreferencesWindow.EventButtonHelpClicked += OpenHelp; // create the main window iMainWindow = new MainWindow(); iMainWindow.Deactivated += MainWindowDeactivated; // create the xapp controller and view iXappController = new XappController(iModel, new Invoker(this.Dispatcher)); iXappController.MainPage.EventShowConfig += OpenPreferences; iXappController.MainPage.EventShowHelp += OpenHelp; iViewer = new ViewerBrowser(iMainWindow.WebBrowser, iXappController.MainPageUri); // create the sys tray icon iFormSysTray = new FormSysTray(iModel); iFormSysTray.EventIconClick += SysTrayIconClick; // start the model System.Drawing.Image image = System.Drawing.Image.FromStream(ResourceManager.Icon.StreamSource); System.IO.MemoryStream stream = new System.IO.MemoryStream(); image.Save(stream, System.Drawing.Imaging.ImageFormat.Png); iModel.Start("linn.co.uk", "Linn", "http://www.linn.co.uk", "http://www.linn.co.uk", stream.ToArray(), "image/png"); bool createdNew; iWaitHandleMainWindow = new EventWaitHandle(false, EventResetMode.ManualReset, "LinnSongcastOpenPreferences", out createdNew); if (!createdNew) { iWaitHandleMainWindow.Set(); //MessageBox.Show("Linn Songcast is already running", "Information", MessageBoxButton.OK, MessageBoxImage.Information); App.Current.Shutdown(0); return; } iWaitHandleExit = new EventWaitHandle(false, EventResetMode.ManualReset, "LinnSongcastExit", out createdNew); Assert.Check(createdNew); iThreadMainWindow = new Thread(ProcessOpenMainWindow); iThreadMainWindow.IsBackground = true; iThreadMainWindow.Start(); iThreadExit = new Thread(ProcessExit); iThreadExit.IsBackground = true; iThreadExit.Start(); Microsoft.Win32.SystemEvents.PowerModeChanged += PowerModeChanged; } catch (SongcastError) { MessageBox.Show("Failed to initialise Linn Songcast Driver", "Error", MessageBoxButton.OK, MessageBoxImage.Error); App.Current.Shutdown(1); } }
public string getImageByUrl(string url, string pcode, string path) { string imcommingLog = ""; imcommingLog += Environment.NewLine + DateTime.Now + Environment.NewLine + "Method Name: getImageByUrl " + Environment.NewLine; imcommingLog += "Request:" + url + Environment.NewLine; string filename = System.IO.Path.GetFileName(url); string imageType = ""; WebResponse response = null; Stream remoteStream = null; StreamReader readStream = null; try { WebRequest request = WebRequest.Create(url); request.Headers.Add("Authorization", "Basic UGluYm94V0E6UGdhbl8wMTA0"); if (request != null) { response = request.GetResponse(); if (response != null) { remoteStream = response.GetResponseStream(); string content_type = response.Headers["Content-type"]; if (content_type == "image/jpeg" || content_type == "image/jpg") { imageType = "jpg"; } else if (content_type == "image/png") { imageType = "png"; } else if (content_type == "image/gif") { imageType = "gif"; } else { imageType = "png"; } string spath = HttpContext.Current.Server.MapPath(path + pcode + "." + imageType); readStream = new StreamReader(remoteStream); System.Drawing.Image img = System.Drawing.Image.FromStream( remoteStream); if (img == null) { return(""); } img.Save(spath, System.Drawing.Imaging.ImageFormat.Jpeg); img.Dispose(); } } } catch (Exception ex) { imcommingLog += "Error:" + ex.Message.ToString() + Environment.NewLine; ErrorHandler.ErrorLog(imcommingLog, ""); return(null); } finally { if (response != null) { response.Close(); } if (remoteStream != null) { remoteStream.Close(); } if (readStream != null) { readStream.Close(); } } imcommingLog += "Image Name:" + pcode + "." + imageType + Environment.NewLine; ErrorHandler.ErrorLog(imcommingLog, ""); return(pcode + "." + imageType); }
private void BulkUpload(bool isPreview) { // data source for preview/audit DataTable auditTable = new DataTable(); auditTable.Columns.AddRange(new DataColumn[] { new DataColumn("PathologyId"), new DataColumn("PathNum"), new DataColumn("Source"), new DataColumn("Target"), new DataColumn("DuplicatePathologyId", typeof(bool)), new DataColumn("DuplicateTargetFileId", typeof(bool)) }); // validation if (!string.IsNullOrEmpty(FILE_DESTINATION_TARGET) && !string.IsNullOrEmpty(FILE_SOURCE_ROOT)) { try { // validate source and files DirectoryInfo sourceDirectory = new DirectoryInfo(FILE_SOURCE_ROOT); if (!sourceDirectory.Exists) { Message.Text = "Source directory does not exists."; return; } FileInfo[] sourceFiles = sourceDirectory.GetFiles(); if (sourceFiles.Count() == 0) { Message.Text = "No Files to copy."; return; } DirectoryInfo targetDirectory = new DirectoryInfo(FILE_DESTINATION_TARGET); // create target upload directory if needed if (!targetDirectory.Exists) { targetDirectory = System.IO.Directory.CreateDirectory(FILE_DESTINATION_TARGET); } // for each source file, upload foreach (FileInfo source_file in sourceFiles) { // locals int pathologyId = int.MinValue; string pathNum = string.Empty; string sourceFullFileName = string.Empty; string targetFileFullName = string.Empty; bool duplicatePathologyId = false; bool duplicateTargetFile = false; string sourceFileName = source_file.Name; sourceFullFileName = source_file.FullName; string fileExtension = source_file.Extension.ToLower(); // validate mime types if (string.IsNullOrEmpty(fileExtension) || !MIME_TYPES.Keys.Contains(fileExtension)) { continue; } string mimeType = MIME_TYPES[fileExtension]; // parse path num pathNum = Path.GetFileNameWithoutExtension(source_file.FullName); // cleanup int foundIndex = pathNum.IndexOf('_'); // PATH-NUM_C.jpg if (foundIndex > -1) { pathNum = pathNum.Substring(0, foundIndex); } // check for Pathology record if (!string.IsNullOrEmpty(pathNum)) { // search for pathology records IEnumerable <Pathology> pathologyRecords = BusinessObject.GetByFields <Pathology>(new Dictionary <string, object> { { Pathology.PathNum, pathNum } }); // do upload, only when single result found if (pathologyRecords.Count() == 1 || (pathologyRecords.Count() > 0 && isPreview)) { // get Pathology record Pathology pathologyRecord = pathologyRecords.First(); pathologyId = (int)pathologyRecord[Pathology.PathologyId]; // don't upload when Table=Pathology + TablePriKey = PathologyId + OriginalFileName = SourceFileName duplicateTargetFile = BusinessObject.GetByFields <UploadedFile>(new Dictionary <string, object> { { UploadedFile.TableName, pathologyRecord.TableName }, { UploadedFile.TablePrimaryKey, pathologyId }, { UploadedFile.OriginalFileName, sourceFileName } }).Count() > 0; // don't upload when if (!duplicateTargetFile || isPreview) { // only do insert when file doesn't exist if (!isPreview) { // create FileUpload record UploadedFile fileUpload = new UploadedFile(); fileUpload[UploadedFile.TableName] = pathologyRecord.TableName; fileUpload[UploadedFile.TablePrimaryKey] = pathologyId; fileUpload[UploadedFile.OriginalFileName] = source_file.Name; fileUpload[UploadedFile.FileExtension] = fileExtension; fileUpload[UploadedFile.FilePath] = targetDirectory.FullName; fileUpload[UploadedFile.FileType] = mimeType; fileUpload[UploadedFile.FileLabel] = FILE_LABEL; fileUpload[UploadedFile.OnFileServer] = 1; fileUpload.Save(); int fileId = (int)fileUpload[UploadedFile.FileId]; targetFileFullName = targetDirectory.FullName + System.IO.Path.DirectorySeparatorChar + fileId + fileExtension; string targetThumbFileName = targetDirectory.FullName + System.IO.Path.DirectorySeparatorChar + fileId + THUMB_EXTENSION + fileExtension; if (!File.Exists(targetFileFullName)) { // upload/copy file source_file.CopyTo(targetFileFullName, false); // create thumbnail System.Drawing.Bitmap sourceBitmap = new System.Drawing.Bitmap(targetFileFullName); System.Drawing.Image sourceFileThumb = sourceBitmap.GetThumbnailImage(THUMB_WIDTH, THUMB_HEIGHT, OnThumbnailCreationFail, IntPtr.Zero); sourceFileThumb.Save(targetThumbFileName); // cleanup after creation sourceFileThumb.Dispose(); sourceBitmap.Dispose(); } } } } } // add audit data object[] rowData = new object[] { pathologyId, pathNum, sourceFullFileName, targetFileFullName, duplicatePathologyId, duplicateTargetFile }; auditTable.Rows.Add(rowData); } // update message LivePanel.Visible = auditTable.Rows.Count > 0; if (isPreview) { if (auditTable.Rows.Count > 0) { Message.Text = "Review Files Below"; } else { Message.Text = "No Files to Preview"; } } else { Message.Text = "Files Below Uploaded"; } } catch (Exception ex) { Message.Text = ex.Message; } } else { Message.Text = "Please check upload settings"; } // update results var dataView = auditTable.DefaultView; dataView.Sort = "PathNum ASC, PathologyId ASC"; AuditGridView.DataSource = dataView; AuditGridView.DataBind(); // display number of acutal uploads TotalFiles.Text = dataView.Count.ToString(); // !important, filter then adjust counts dataView.RowFilter = "PathologyId > -1 AND DuplicateTargetFileId = 0"; TotalToUploadFiles.Text = dataView.Count.ToString(); TotalUploaded.Text = isPreview ? "0" : dataView.Count.ToString(); }
public ActionResult Edit(ProductModels model) { try { List <string> ListNotChangeImg = new List <string>(); byte[] photoByte = null; if (!string.IsNullOrEmpty(model.ImageURL)) { model.ImageURL = model.ImageURL.Replace(Commons._PublicImages, "").Replace(Commons.Image200_100, ""); model.RawImageUrl = model.ImageURL; } if (model.PictureUpload != null && model.PictureUpload.ContentLength > 0) { Byte[] imgByte = new Byte[model.PictureUpload.ContentLength]; model.PictureUpload.InputStream.Read(imgByte, 0, model.PictureUpload.ContentLength); model.PictureByte = imgByte; model.RawImageUrl = Guid.NewGuid() + Path.GetExtension(model.PictureUpload.FileName); model.PictureUpload = null; photoByte = imgByte; if (!string.IsNullOrEmpty(model.ImageURL)) { model.ImageURL = model.ImageURL.Replace(Commons._PublicImages, "").Replace(Commons.Image200_100, ""); ListNotChangeImg.Add(model.ImageURL); } } if (!ModelState.IsValid) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(PartialView("_Edit", model)); } if (!string.IsNullOrEmpty(model.RawImageUrl)) { model.ListImageUrl.Add(model.RawImageUrl); } //======== Dictionary <int, byte[]> lstImgByte = new Dictionary <int, byte[]>(); var ListImage = model.ListImg.Where(x => !x.IsDelete).ToList(); foreach (var item in ListImage) { if (item.PictureUpload != null && item.PictureUpload.ContentLength > 0) { if (!string.IsNullOrEmpty(item.ImageURL)) { item.ImageURL = item.ImageURL.Replace(Commons._PublicImages, "").Replace(Commons.Image200_100, ""); ListNotChangeImg.Add(item.ImageURL); } Byte[] imgByte = new Byte[item.PictureUpload.ContentLength]; item.PictureUpload.InputStream.Read(imgByte, 0, item.PictureUpload.ContentLength); item.PictureByte = imgByte; item.ImageURL = Guid.NewGuid() + Path.GetExtension(item.PictureUpload.FileName); item.PictureUpload = null; lstImgByte.Add(item.OffSet, imgByte); model.ListImageUrl.Add(item.ImageURL); } else { if (!string.IsNullOrEmpty(item.ImageURL)) { item.ImageURL = item.ImageURL.Replace(Commons._PublicImages, "").Replace(Commons.Image200_100, ""); model.ListImageUrl.Add(item.ImageURL); } } } //==================== string msg = ""; var result = _factory.UpdateProduct(model, ref msg); if (result) { if (ListNotChangeImg != null && ListNotChangeImg.Any()) { //Delete image on forder foreach (var item in ListNotChangeImg) { if (!item.Equals(Commons.Image200_100)) { var filePath = Server.MapPath("~/Uploads/Images/Product/" + item); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } } } if (!string.IsNullOrEmpty(model.RawImageUrl) && model.PictureByte != null) { var path = Server.MapPath("~/Uploads/Images/Product/" + model.RawImageUrl); MemoryStream ms = new MemoryStream(photoByte, 0, photoByte.Length); ms.Write(photoByte, 0, photoByte.Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImageProduct(imageTmp, path, model.RawImageUrl, ref photoByte); } foreach (var item in ListImage) { if (!string.IsNullOrEmpty(item.ImageURL) && item.PictureByte != null) { var path = Server.MapPath("~/Uploads/Images/Product/" + item.ImageURL); MemoryStream ms = new MemoryStream(lstImgByte[item.OffSet], 0, lstImgByte[item.OffSet].Length); ms.Write(lstImgByte[item.OffSet], 0, lstImgByte[item.OffSet].Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImageProduct(imageTmp, path, item.ImageURL, ref photoByte); } } return(RedirectToAction("Index")); } else { ModelState.AddModelError("Name", msg); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(PartialView("_Edit", model)); } } catch (Exception ex) { NSLog.Logger.Error("Product_Edit: ", ex); model = GetDetail(model.ID); Response.StatusCode = (int)HttpStatusCode.BadRequest; return(new HttpStatusCodeResult(400, ex.Message)); } }
private void getlinkedinuserdataSer(string access_token) { using (var client = new HttpClient()) { var urlProfile = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,email-address)?format=json&oauth2_access_token=" + access_token; var response = client.GetAsync(urlProfile).Result; if (response.IsSuccessStatusCode) { // by calling .Result you are performing a synchronous call var responseContent = response.Content; // by calling .Result you are synchronously reading the result string responseString = responseContent.ReadAsStringAsync().Result; LinkedinUserOutputData serStatus = JsonConvert.DeserializeObject <LinkedinUserOutputData>(responseString); if (site_islem.BireyselKayitOlKontrol(serStatus.emailAddress)) { FormsAuthentication.SetAuthCookie(serStatus.emailAddress, true); Session["giris_yapan"] = serStatus.emailAddress; if (Session["oturum_sonrasi_sayfa"] != null) { Response.Redirect(Session["oturum_sonrasi_sayfa"].ToString()); } else { Response.RedirectToRoute("Home"); } return; } string resimadi = "Eduadvisor-uye-" + DateTime.Now.ToString("yyyyMMddHmmss"); try { WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(serStatus.pictureUrl); MemoryStream ms = new MemoryStream(bytes); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); string extension = ""; if (ImageFormat.Jpeg.Equals(img.RawFormat)) { extension = ".jpg"; } else if (ImageFormat.Png.Equals(img.RawFormat)) { extension = ".png"; } resimadi += extension; if (!extension.Equals("")) { img.Save("C:/Inetpub/vhosts/eduadvisor.co.uk/httpdocs/Content/img/kul_profil/" + resimadi); } else { resimadi = "profil.png"; } } catch (Exception) { resimadi = "profil.png"; } string sonuc = site_islem.BireyselKayitOl(serStatus.firstName, serStatus.lastName, resimadi, serStatus.emailAddress, islem.randomSifreUret(), true, 3); if (sonuc.Equals("1") || sonuc.Equals("-9")) { Session["giris_yapan"] = serStatus.emailAddress; } } } if (Session["oturum_sonrasi_sayfa"] != null) { Response.Redirect(Session["oturum_sonrasi_sayfa"].ToString()); } else { Response.RedirectToRoute("Home"); } }
protected void UploadButton_Click(object sender, EventArgs e) { ///'遍历File表单元素 HttpFileCollection files = HttpContext.Current.Request.Files; /// '状态信息 System.Text.StringBuilder strMsg = new System.Text.StringBuilder("培训班为:" + qishu_dro.SelectedValue + "<br/>"); strMsg.Append("上传的文件分别是:<hr color='red'/>"); int count = 0; try { for (int iFile = 0; iFile < files.Count; iFile++) { ///'检查文件扩展名字 HttpPostedFile postedFile = files[iFile]; string fileName, fileExtension; fileName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Today.GetDateTimeFormats('D')[0].ToString() + System.IO.Path.GetExtension(postedFile.FileName); if (fileName != "") { fileExtension = System.IO.Path.GetExtension(fileName); strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>"); strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>"); strMsg.Append("上传文件的文件名:" + fileName + "<br>"); strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>"); ///'可根据扩展名字的不同保存到不同的文件夹 ///注意:可能要修改你的文件夹的匿名写入权限。 postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("../images/") + fileName); System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Request.MapPath("../images/") + fileName); string strName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Today.GetDateTimeFormats('D')[0].ToString() + "_small_" + System.IO.Path.GetExtension(postedFile.FileName); //string strName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName) + DateTime.Today.GetDateTimeFormats('D')[0].ToString() + System.IO.Path.GetExtension(postedFile.FileName); string strResizePicName = System.Web.HttpContext.Current.Request.MapPath("../images/") + strName; Maticsoft.BLL.photos ph = new BLL.photos(); string str = ph.photoscompress(imgPhoto, 400, 300, strResizePicName); if (str == "保存成功") { Maticsoft.Model.photos ph_m = new Model.photos(); ph_m.ContentType = postedFile.ContentType.ToString(); ph_m.postedFileFileName = postedFile.FileName; ph_m.FileName = strName; ph_m.fileExtension = fileExtension; ph_m.qishu = qishu_dro.SelectedValue; if (fenlei_txt.Text == "") { ph_m.fenlei2 = fenlei_dro.SelectedValue; } else { ph_m.fenlei2 = fenlei_txt.Text.Trim(); } Maticsoft.BLL.photos pho = new BLL.photos(); count += pho.Add(ph_m); } else { strMsg.Append(str); } } } strMsg.Append("共上传图片" + count + "张"); strStatus.Text = strMsg.ToString(); } catch (System.Exception Ex) { strStatus.Text = Ex.Message; } }
public void LoadImage() { //using var Trace = new Trace(); //This c# 8.0 using feature will auto dispose when the function is done. //since having a lot of trouble with image access problems, try to wait for image to become available, validate the image and load //a single time rather than multiple Global.WaitFileAccessResult result = new Global.WaitFileAccessResult(); this._valid = false; bool validate = !this._Temp; try { if (!string.IsNullOrEmpty(this.image_path) && File.Exists(this.image_path)) { Stopwatch sw = Stopwatch.StartNew(); do { int MaxWaitMS = 0; int MaxRetries = 0; if (this._Temp) { MaxWaitMS = 500; MaxRetries = 2; } else { MaxWaitMS = 10000; MaxRetries = 100; } result = Global.WaitForFileAccess(this.image_path, FileAccess.Read, FileShare.None, MaxWaitMS, AppSettings.Settings.loop_delay_ms, true, 4096, MaxRetries); this.FileLockMS = sw.ElapsedMilliseconds; this.FileLockErrRetryCnt += result.ErrRetryCnt; if (result.Success) { try { sw.Restart(); // Open a FileStream object using the passed in safe file handle. using (FileStream fileStream = new FileStream(result.Handle, FileAccess.Read)) { using System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream, true, validate); this._valid = img != null && img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg) && img.Width > 0 && img.Height > 0; this.FileLoadMS = sw.ElapsedMilliseconds; if (!this._valid) { LastError = $"Error: Image file is not jpeg? {this.image_path}"; AITOOL.Log(LastError); break; } else { this.Width = img.Width; this.Height = img.Height; this.DPI = img.HorizontalResolution; if (this._Temp) { this.FileLoadMS = sw.ElapsedMilliseconds; } else { using MemoryStream ms = new MemoryStream(); //fileStream.CopyTo(ms); img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); this.ImageByteArray = ms.ToArray(); this.FileSize = this.ImageByteArray.Length; this.FileLoadMS = sw.ElapsedMilliseconds; this._valid = true; AITOOL.Log($"Trace: Image file is valid. Resolution={this.Width}x{this.Height}, LockMS={this.FileLockMS}ms (max={MaxWaitMS}ms), retries={this.FileLockErrRetryCnt}, size={Global.FormatBytes(ms.Length)}: {Path.GetFileName(this.image_path)}"); } break; } } } catch (Exception ex) { this._valid = false; LastError = $"Error: Image is corrupt. LockMS={this.FileLockMS}ms (max={MaxWaitMS}ms), retries={this.FileLockErrRetryCnt}: {Path.GetFileName(this.image_path)} - {ex.Msg()}"; } finally { this._loaded = true; if (!result.Handle.IsClosed) { result.Handle.Close(); result.Handle.Dispose(); } } } else { if (this._Temp) { LastError = $"Debug: Could not gain access to the image in {result.TimeMS}ms, retries={result.ErrRetryCnt}: {Path.GetFileName(this.image_path)}"; } else { LastError = $"Error: Could not gain access to the image in {result.TimeMS}ms, retries={result.ErrRetryCnt}: {Path.GetFileName(this.image_path)}"; } } if (this._Temp) //only one loop { break; } } while ((!result.Success || !this._valid) && sw.ElapsedMilliseconds < 30000); } else { LastError = "Debug: File has been deleted: " + this.image_path; } } catch (Exception ex) { LastError = $"Error: {ex.Msg()}"; } finally { if (result.Handle != null && !result.Handle.IsInvalid && !result.Handle.IsClosed) { result.Handle.Close(); result.Handle.Dispose(); } if (!this._valid && !string.IsNullOrEmpty(LastError)) { AITOOL.Log(LastError); } } }
public static string GetMimeType(System.Drawing.Image image) { System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); return(codecs.FirstOrDefault(codec => codec.FormatID == image.RawFormat.Guid)?.MimeType ?? "image/jpg"); }
/// <summary> /// Loads Memory Files form the Object Package /// </summary> public void LoadMemories() { memories = new Hashtable(); //if (BasePackage==null) return; Registry reg = Helper.WindowsRegistry; ArrayList list = new ArrayList(); Interfaces.Files.IPackedFileDescriptor pfd; SimPe.PackedFiles.Wrapper.ExtObjd objd = new SimPe.PackedFiles.Wrapper.ExtObjd(); SimPe.PackedFiles.Wrapper.Str str = new SimPe.PackedFiles.Wrapper.Str(); FileTable.FileIndex.Load(); Interfaces.Scenegraph.IScenegraphFileIndexItem[] items = FileTable.FileIndex.FindFileDiscardingGroup(Data.MetaData.OBJD_FILE, 0x00000000000041A7); string max = " / " + items.Length.ToString(); int ct = 0; if (items.Length != 0) //found anything? { bool wasrunning = WaitingScreen.Running; WaitingScreen.Wait(); try { foreach (Interfaces.Scenegraph.IScenegraphFileIndexItem item in items) { ct++; if (ct % 137 == 1) { WaitingScreen.UpdateMessage(ct.ToString() + max); } pfd = item.FileDescriptor; string name = ""; objd.ProcessData(item); if (memories.Contains(objd.Guid)) { continue; } try { Interfaces.Scenegraph.IScenegraphFileIndexItem[] sitems = FileTable.FileIndex.FindFile(Data.MetaData.CTSS_FILE, pfd.Group, objd.CTSSInstance, null); if (sitems.Length > 0) { str.ProcessData(sitems[0]); SimPe.PackedFiles.Wrapper.StrItemList strs = str.LanguageItems(Helper.WindowsRegistry.LanguageCode); if (strs.Length > 0) { name = strs[0].Title; } //not found? if (name == "") { strs = str.LanguageItems(1); if (strs.Length > 0) { name = strs[0].Title; } } } } catch (Exception) { } //still no name? if (name == "") { name = objd.FileName; } #if DEBUG IAlias a = new Alias(objd.Guid, name, "{1}: {name} (0x{id})"); #else IAlias a = new Alias(objd.Guid, name, "{1}: {name}"); #endif object[] o = new object[3]; o[0] = pfd; o[1] = (Data.ObjectTypes)objd.Type; o[2] = null; SimPe.PackedFiles.Wrapper.Picture pic = new SimPe.PackedFiles.Wrapper.Picture(); Interfaces.Scenegraph.IScenegraphFileIndexItem[] iitems = FileTable.FileIndex.FindFile(Data.MetaData.SIM_IMAGE_FILE, pfd.Group, 1, null); if (iitems.Length > 0) { pic.ProcessData(iitems[0]); System.Drawing.Image img = pic.Image; o[2] = img; WaitingScreen.Update(img, ct.ToString() + max); } a.Tag = o; if (!memories.Contains(objd.Guid)) { memories.Add(objd.Guid, a); } } //foreach item } finally { if (!wasrunning) { WaitingScreen.Stop(); } } } // if items>0 //System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; }
public static void ExportByTemplete(IList <modExcelRangeData> list, string sheetname) { try { string filename = clsLxms.GetParameterValue("EXCEL_TEMPLETE_FILE"); if (!File.Exists(filename)) { MessageBox.Show(clsTranslate.TranslateString("Can not find the templete file") + ": \r\n" + filename, clsTranslate.TranslateString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string destfilename = GetExportFilePath(0); if (File.Exists(destfilename)) { File.Delete(destfilename); } Util.retValue1 = destfilename; File.Copy(filename, destfilename); Excel.Application m_objExcel = new Excel.Application(); m_objExcel.DisplayAlerts = false; Excel.Workbooks m_objBooks = m_objExcel.Workbooks; m_objBooks.Open(destfilename, 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); Excel.Workbook m_objBook = (Excel.Workbook)m_objBooks.get_Item(1); Excel.Sheets sm_objSheets = (Excel.Sheets)m_objBook.Worksheets; Excel.Worksheet m_objSheet = (Excel.Worksheet)sm_objSheets.get_Item(sheetname); for (int i = sm_objSheets.Count; i >= 1; i--) { Excel.Worksheet m_Sheet = sm_objSheets.get_Item(i); if (m_Sheet.Name.ToLower().CompareTo(sheetname.ToLower()) != 0) { m_Sheet.Delete(); } } Excel.Range range; foreach (modExcelRangeData mod in list) { range = (Excel.Range)m_objSheet.get_Range(mod.CellBegin, mod.CellEnd); if (!mod.Is_Pic) { range.Value = mod.CellValue; } else { if (!string.IsNullOrEmpty(mod.CellValue) && File.Exists(mod.CellValue)) { System.Drawing.Image im = System.Drawing.Image.FromFile(mod.CellValue); double iLeft = range.Left + 1; double iTop = range.Top + 1; double iWidth = range.Width - 2; double iHeight = range.Height - 2; if (im.Width <= range.Width) { iWidth = im.Width; iLeft = range.Left + (range.Width - im.Width) / 2; } if (im.Height <= range.Height) { iHeight = im.Height; iTop = range.Top + (range.Height - im.Height) / 2; } im.Dispose(); m_objSheet.Activate(); range.Select(); m_objSheet.Shapes.AddPicture(mod.CellValue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, (float)iLeft, (float)iTop, (float)iWidth, (float)iHeight); } } } m_objSheet.Activate(); m_objExcel.Visible = true; } catch (System.Exception ex) { MessageBox.Show(ex.Message, clsTranslate.TranslateString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } }
/// <summary> /// Get file information /// </summary> /// <param name="path"></param> /// <returns></returns> private string GetInfo(string path) { if (!IsInRootPath(path)) { return(Error("Attempt to view file outside root path")); } if (!System.IO.File.Exists(Server.MapPath(path)) && !Directory.Exists(Server.MapPath(path))) { return(Error("File not found")); } StringBuilder sb = new StringBuilder(); FileAttributes attr = System.IO.File.GetAttributes(Server.MapPath(path)); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath(path)); sb.AppendLine("{"); sb.AppendLine("\"Path\": \"" + path + "\","); sb.AppendLine("\"Filename\": \"" + DirInfo.Name + "\","); sb.AppendLine("\"File Type\": \"dir\","); sb.AppendLine("\"Preview\": \"" + IconDirectory + "_Open.png\","); sb.AppendLine("\"Properties\": {"); sb.AppendLine("\"Date Created\": \"" + DirInfo.CreationTime.ToString() + "\", "); sb.AppendLine("\"Date Modified\": \"" + DirInfo.LastWriteTime.ToString() + "\", "); sb.AppendLine("\"Height\": 0,"); sb.AppendLine("\"Width\": 0,"); sb.AppendLine("\"Size\": 0 "); sb.AppendLine("},"); sb.AppendLine("\"Error\": \"\","); sb.AppendLine("\"Code\": 0 "); sb.AppendLine("}"); } else { FileInfo fileInfo = new FileInfo(Server.MapPath(path)); sb.AppendLine("{"); sb.AppendLine("\"Path\": \"" + path + "\","); sb.AppendLine("\"Filename\": \"" + fileInfo.Name + "\","); sb.AppendLine("\"File Type\": \"" + fileInfo.Extension.Replace(".", "") + "\","); if (IsImage(fileInfo)) { sb.AppendLine("\"Preview\": \"" + path + "\","); } else { sb.AppendLine("\"Preview\": \"" + String.Format("{0}{1}.png", IconDirectory, fileInfo.Extension.Replace(".", "")) + "\","); } sb.AppendLine("\"Properties\": {"); sb.AppendLine("\"Date Created\": \"" + fileInfo.CreationTime.ToString() + "\", "); sb.AppendLine("\"Date Modified\": \"" + fileInfo.LastWriteTime.ToString() + "\", "); if (IsImage(fileInfo)) { using (System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(path))) { sb.AppendLine("\"Height\": " + img.Height.ToString() + ","); sb.AppendLine("\"Width\": " + img.Width.ToString() + ","); } } sb.AppendLine("\"Size\": " + fileInfo.Length.ToString() + " "); sb.AppendLine("},"); sb.AppendLine("\"Error\": \"\","); sb.AppendLine("\"Code\": 0 "); sb.AppendLine("}"); } return(sb.ToString()); }
public ActionResult Create(ProductModels model) { try { byte[] photoByte = null; if (model.PictureUpload != null && model.PictureUpload.ContentLength > 0) { Byte[] imgByte = new Byte[model.PictureUpload.ContentLength]; model.PictureUpload.InputStream.Read(imgByte, 0, model.PictureUpload.ContentLength); model.PictureByte = imgByte; model.RawImageUrl = Guid.NewGuid() + Path.GetExtension(model.PictureUpload.FileName); model.PictureUpload = null; photoByte = imgByte; } if (!ModelState.IsValid) { return(View(model)); } if (!string.IsNullOrEmpty(model.RawImageUrl)) { model.ListImageUrl.Add(model.RawImageUrl); } //======== Dictionary <int, byte[]> lstImgByte = new Dictionary <int, byte[]>(); var ListImage = model.ListImg.Where(x => !x.IsDelete).ToList(); foreach (var item in ListImage) { if (item.PictureUpload != null && item.PictureUpload.ContentLength > 0) { Byte[] imgByte = new Byte[item.PictureUpload.ContentLength]; item.PictureUpload.InputStream.Read(imgByte, 0, item.PictureUpload.ContentLength); item.PictureByte = imgByte; item.ImageURL = Guid.NewGuid() + Path.GetExtension(item.PictureUpload.FileName); item.PictureUpload = null; lstImgByte.Add(item.OffSet, imgByte); model.ListImageUrl.Add(item.ImageURL); } } //==================== string msg = ""; bool result = _factory.InsertProduct(model, ref msg); if (result) { if (!string.IsNullOrEmpty(model.RawImageUrl) && model.PictureByte != null) { var path = Server.MapPath("~/Uploads/Images/Product/" + model.RawImageUrl); MemoryStream ms = new MemoryStream(photoByte, 0, photoByte.Length); ms.Write(photoByte, 0, photoByte.Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImageProduct(imageTmp, path, model.RawImageUrl, ref photoByte); } foreach (var item in ListImage) { if (!string.IsNullOrEmpty(item.ImageURL) && item.PictureByte != null) { var path = Server.MapPath("~/Uploads/Images/Product/" + item.ImageURL); MemoryStream ms = new MemoryStream(lstImgByte[item.OffSet], 0, lstImgByte[item.OffSet].Length); ms.Write(lstImgByte[item.OffSet], 0, lstImgByte[item.OffSet].Length); System.Drawing.Image imageTmp = System.Drawing.Image.FromStream(ms, true); ImageHelper.Me.SaveCroppedImageProduct(imageTmp, path, item.ImageURL, ref photoByte); } } return(RedirectToAction("Index")); } else { ModelState.AddModelError("Name", msg); return(View(model)); } } catch (Exception ex) { NSLog.Logger.Error("House_Create: ", ex); return(new HttpStatusCodeResult(400, ex.Message)); } }
public void FacebookProfil(string code) { if (code != null) { string state = ""; string type = ""; dynamic token = Face.GetAccessToken(code, state, type); FacebookProfilModel Profil = Face.GetUserInfo(token); if (site_islem.BireyselKayitOlKontrol(Profil.Email)) { FormsAuthentication.SetAuthCookie(Profil.Email, true); Session["giris_yapan"] = Profil.Email; if (Session["oturum_sonrasi_sayfa"] != null) { Response.Redirect(Session["oturum_sonrasi_sayfa"].ToString()); } else { Response.RedirectToRoute("Home"); } return; } string resimadi = "Eduadvisor-uye-" + DateTime.Now.ToString("ddMMyyyyHHmmssffff"); try { WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(string.Format("http://graph.facebook.com/{0}/picture", Profil.Id)); MemoryStream ms = new MemoryStream(bytes); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); string extension = ""; if (ImageFormat.Jpeg.Equals(img.RawFormat)) { extension = ".jpg"; } else if (ImageFormat.Png.Equals(img.RawFormat)) { extension = ".png"; } resimadi += extension; if (!extension.Equals("")) { img.Save("C:/Inetpub/vhosts/eduadvisor.co.uk/httpdocs/Content/img/kul_profil/" + resimadi); } else { resimadi = "profil.png"; } } catch (Exception) { resimadi = "profil.png"; } string sonuc = site_islem.BireyselKayitOl(Profil.isim, Profil.soyisim, resimadi, Profil.Email, islem.randomSifreUret(), true, 0); if (sonuc.Equals("1") || sonuc.Equals("-9")) { FormsAuthentication.SetAuthCookie(Profil.Email, true); Session["giris_yapan"] = Profil.Email; } } if (Session["oturum_sonrasi_sayfa"] != null) { Response.Redirect(Session["oturum_sonrasi_sayfa"].ToString()); } else { Response.RedirectToRoute("Home"); } }
public static System.Drawing.Image RedimImage(System.Drawing.Image image, System.Drawing.Size size, long minByteWeight, long maxByteWeight) { return(RedimImage(image, size.Width, size.Height, minByteWeight, maxByteWeight)); }
//修改模块信息 protected void btnModify_Click(object sender, EventArgs e) { if (UpImage.PostedFile.ContentLength == 0) { string sqlstr = "update tb_Module set ModuleName='" + txtModTitle.Text + "',ModuleDescribe='" + Describe.Text + "' where ModuleID='" + Request["ModuleID"].ToString() + "'"; if (sqlBind.DataCom(sqlstr)) { Response.Write("<script>alert('修改成功');window.location.href='ManageMudole.aspx';</script>"); } else { Response.Write("<script>alert('修改失败');history.back();</script>"); } } else { FileInfo file1 = new FileInfo(UpImage.PostedFile.FileName); if (file1.Extension != ".bmp" && file1.Extension != ".jpg" && file1.Extension != ".jpeg" && file1.Extension != ".png" && file1.Extension != ".gif") { Response.Write("<script>alert('上传的图片格式应为bmp/jpg/jpeg/png/gif格式');history.back(-1);</script>"); return; } double size = UpImage.PostedFile.ContentLength; if (size >= 1024000) { Response.Write("<script>alert('添加失败!(图片容量请不要超过1MB)')</script>"); return; } string name = this.Image1.ImageUrl.Substring(14); //原来图片的URL string webFilePath = Server.MapPath("~/NewsImages/" + name); //用来删除原有的图片 string indexpath = Server.MapPath(this.Image1.ImageUrl); string filename = UpImage.PostedFile.FileName; filename = System.IO.Path.GetFileName(filename); //改文件名 int index = filename.LastIndexOf("."); string lastName = filename.Substring(index, filename.Length - index);//获得文件后缀类型 //新文件名称,以时间年月日时分秒作为文件名 string newname = "BBSSubject" + DateTime.Now.ToString("yyyyMMddhhmmss") + lastName; string newpath = Server.MapPath("~/NewsImages/" + newname);//用来保存新上传的图片 string newindexpath = Server.MapPath("~/IndexImages/" + newname); System.IO.FileInfo file = new System.IO.FileInfo(webFilePath); System.IO.FileInfo indexfile = new System.IO.FileInfo(indexpath); if (file.Exists) { file.Delete();//删除 } if (indexfile.Exists) { indexfile.Delete();//删除 } if (!File.Exists(newpath)) { UpImage.SaveAs(newpath);// 使用 SaveAs 方法保存文件 System.Drawing.Image image = System.Drawing.Image.FromFile(newpath); float a = image.Width / image.Height; if (a > 5) { image.Dispose(); File.Delete(newpath); Response.Write("<script>alert('高宽比例不合适');</script>"); return; } System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image, 80, 80); if (!File.Exists(newindexpath)) { bmp.Save(newindexpath); } image.Dispose(); bmp.Dispose(); File.Delete(newpath); } string title = Server.HtmlEncode(txtModTitle.Text.Trim()); string describe = Server.HtmlEncode(Describe.Text.Trim()); string sqlstr = "update tb_Module set ModuleName='" + title + "',ModuleDescribe='" + describe + "',ModuleImage='" + newname + "' where ModuleID='" + Request["ModuleID"].ToString() + "'"; if (sqlBind.DataCom(sqlstr)) { Response.Write("<script>alert('修改成功');window.location.href='ManageMudole.aspx';</script>"); } else { Response.Write("<script>alert('修改失败');history.back();</script>"); } } }
public static string GetMimeType(this System.Drawing.Image image) { return(image.RawFormat.GetMimeType()); }
private static string CreateThumbnail(string strImage) { var blnCreate = true; var strThumbnail = strImage.Replace(Path.GetFileName(strImage), "thumbnail_" + Path.GetFileName(strImage)); //check if image has changed if (File.Exists(strThumbnail)) { if (File.GetLastWriteTime(strThumbnail) == File.GetLastWriteTime(strImage)) { blnCreate = false; } } if (blnCreate) { const int intSize = 150; //size of the thumbnail Image objImage; try { objImage = Image.FromFile(strImage); //scale the image to prevent distortion int intHeight; int intWidth; double dblScale; if (objImage.Height > objImage.Width) { //The height was larger, so scale the width dblScale = (double)intSize / objImage.Height; intHeight = intSize; intWidth = Convert.ToInt32(objImage.Width * dblScale); } else { //The width was larger, so scale the height dblScale = (double)intSize / objImage.Width; intWidth = intSize; intHeight = Convert.ToInt32(objImage.Height * dblScale); } //create the thumbnail image var objThumbnail = objImage.GetThumbnailImage(intWidth, intHeight, null, IntPtr.Zero); //delete the old file ( if it exists ) if (File.Exists(strThumbnail)) { File.Delete(strThumbnail); } //save the thumbnail image objThumbnail.Save(strThumbnail, objImage.RawFormat); //set the file attributes File.SetAttributes(strThumbnail, FileAttributes.Normal); File.SetLastWriteTime(strThumbnail, File.GetLastWriteTime(strImage)); //tidy up objImage.Dispose(); objThumbnail.Dispose(); } catch (Exception ex) //problem creating thumbnail { Logger.Error(ex); } } strThumbnail = Globals.ApplicationPath + "/" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\")); strThumbnail = strThumbnail.Replace("\\", "/"); //return thumbnail filename return(strThumbnail); }
public HttpResponseMessage UpdateProfile([FromBody] EmployeeModel objEmployee) { IP = System.Configuration.ConfigurationManager.AppSettings["IP"]; var re = Request; var headers = re.Headers; if (headers.Contains("token")) { token = headers.GetValues("token").First(); } var result = Authtoken.checkToken(token); if (result == true) { if (objEmployee.base64image == null) { string pic = objEmployee.profilePic; objEmployee.profilePic = pic.Replace(IP, ""); objemployeeDL.updeempprofile(objEmployee); dt = objemployeeDL.getEmployesbyUserID(objEmployee); foreach (DataRow row in dt.Rows) { string url = dt.Rows[0]["profilePic"].ToString(); //need to set value to NewColumn column row["profilePic"] = IP + url; } var resp = Request.CreateResponse <ResponseModel>(HttpStatusCode.OK, new ResponseModel() { message = "Your profile Updated successfully", output = dt, statuscode = Convert.ToInt16(HttpStatusCode.OK) }); return(resp); } else { string baseencode = objEmployee.base64image; // Convert Base64 String to byte[] byte[] imageBytes = Convert.FromBase64String(baseencode); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); // Convert byte[] to Image string filename = "/uploads/images/profilepics/" + Authtoken.GeneratePin() + AuthorizationToken.GetTimestamp(DateTime.Now) + ".png"; ms.Write(imageBytes, 0, imageBytes.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); image.Save(HttpContext.Current.Server.MapPath(filename), System.Drawing.Imaging.ImageFormat.Png); objEmployee.profilePic = filename; objemployeeDL.updeempprofile(objEmployee); dt = objemployeeDL.getEmployesbyUserID(objEmployee); foreach (DataRow row in dt.Rows) { string url = dt.Rows[0]["profilePic"].ToString(); //need to set value to NewColumn column row["profilePic"] = IP + url; } var resp = Request.CreateResponse <ResponseModel>(HttpStatusCode.OK, new ResponseModel() { message = "Your profile Updated successfully", output = dt, statuscode = Convert.ToInt16(HttpStatusCode.OK) }); return(resp); } } else { var resp = Request.CreateResponse <ResponseModel>(HttpStatusCode.OK, new ResponseModel() { message = "UnAuthorized", statuscode = Convert.ToInt16(HttpStatusCode.OK), error = true }); return(resp); } }
// GET api/Websites/5 public string Get(int id, int amt, string printdata = " ") { try { Global.bAppCallRunning = true; switch (id) { case 1: //Init Cash { Log.WriteEJData("CASH ACCEPT STATE CALL"); if (amt == 0) { Log.WriteEJData("APP PASS AMOUNT IS ZERO"); RDresult = "Please enter valid amount."; } else if ((amt % 10) == 0) { Log.WriteEJData("CASH ACCEPTANCE STARTED"); if (Global.objCash.StartAccept(amt)) { RDresult = "Place notes one after another."; //Cash Accepting Mode } else { Log.WriteEJData("CASH ACCEPT DEVICE DISCONNECTED"); RDresult = "Device disconnected"; //Lokesh Added[25Sept2018] } } else { Log.WriteEJData("AMOUNT IS NOT IN MULTIPLE OF Rupee 10"); RDresult = "Amount should be multiple of 10"; } } break; case 2: //Receipt Print { if (amt != 1) { Log.WriteEJData("PRINT RECEIPT METHOD CALL"); if (Global.RPStatus == "Printer Offline") { Log.WriteEJData("RECEIPT PRINTER OFFLINE"); Log.WriteLog("On Start Print Printer is Offline", "PrintReceipt"); Log.WriteEJData("TRY FOR OFFLINE RECOVERY"); if (!Global.objRP.InitializeReceipt()) { Buffer = ""; Global.RPStatus = "Printer Offline"; Log.WriteEJData("RECEIPT PRINTER OFFLINE AFTER RECOVERY"); RDresult = "Printer Offline"; } else { Log.WriteEJData("RECEIPT PRINTER ONLINE AFTER RECOVERY"); } } string iRPStatus = Global.objRP.GetPrinterStatus(); if (iRPStatus == "Printer Online" || iRPStatus == "Paper Low") { printdata = Buffer + printdata; if (printdata == "") { Log.WriteEJData("RECEIPT DATA NOT RECEIVED"); Log.WriteLog("No Data Received to print", "PrintReceipt"); RDresult = "Print Data Not Found"; } else { string[] data = printdata.Split('@'); string datatoprint = ""; //\x1b|1B\r\n"; char c; for (int i = 0; i < data.Length; i++) { if (data[i].Contains("~~~")) { c = (char)(Convert.ToInt32(data[i].Substring(data[i].IndexOf("~~~") + 3))); data[i] = "" + c; } datatoprint += data[i]; } if (Global.objRP.PrintReceipt(datatoprint)) //amt is logo number to print with receipt { Log.WriteEJData("RECEIPT PRINTED SUCCESSFULLY"); Buffer = ""; if (Global.objRP.CutRPPaper()) { RDresult = "Print OK"; } else { RDresult = "Print Successful but failed to cut"; } } else { Log.WriteEJData("RECEIPT PRINT FAILURE"); Buffer = ""; return("Printing failed"); } } } else { Log.WriteEJData("RECEIPT PRINTER ERROR STATUS: " + Global.RPStatus); Buffer = ""; RDresult = Global.RPStatus; } } else { if (printdata == "") { Log.WriteEJData("PRINT DATA NOT PROVIDED AND Amt == 1"); Log.WriteLog("No Data Received to print", "PrintReceipt"); RDresult = "Print Data Not Found"; } else { // Global.objRP.PrintReceipt(printdata); Buffer += printdata; RDresult = "MORE"; } } } break; case 3: //Get RP Status { Log.WriteEJData("GET RECEIPT PRINTER STATUS METHOD CALL"); if (Global.RPStatus == "Printer Offline") { Log.WriteEJData("RECEIPT PRINTER OFFLINE"); Log.WriteLog("On Start Printer Statue is Offline", "PrintReceipt"); Log.WriteEJData("RECEIPT PRINTER OFFLINE TRY FOR RECOVERY"); if (!Global.objRP.InitializeReceipt()) { Global.RPStatus = "Printer Offline"; Log.WriteEJData("RECEIPT PRINTER STILL OFFLINE AFTER RECOVERY"); RDresult = "Printer Offline"; } else { Global.RPStatus = Global.objRP.GetPrinterStatus(); Log.WriteEJData("RECEIPT PRINTER STATUS IS: " + Global.RPStatus); RDresult = Global.RPStatus; } } else { Global.RPStatus = Global.objRP.GetPrinterStatus(); Log.WriteEJData("RECEIPT PRINTER STATUS IS: " + Global.RPStatus); RDresult = Global.RPStatus; } } break; case 4: //Get Note Details { Log.WriteEJData("GET NOTE DETAIL METHOD CALL"); string RetCount = Global.NoteDenomination[0].ToString() + "#"; RetCount += Global.NoteDenomination[1].ToString() + "#"; RetCount += Global.NoteDenomination[2].ToString() + "#"; RetCount += Global.NoteDenomination[3].ToString() + "#"; RetCount += Global.NoteDenomination[4].ToString() + "#"; RetCount += Global.NoteDenomination[5].ToString() + "#"; RetCount += Global.NoteDenomination[6].ToString(); Log.WriteEJData("ACCEPTED NOTE DETAILS ARE : " + RetCount); RDresult = RetCount; } break; case 5: //Stop Note Accept { Log.WriteEJData("STOP NOTE ACCEPT METHOD CALL"); Global.objCash.StopAccept(); string RetCount = Global.NoteDenomination[0].ToString() + "#"; RetCount += Global.NoteDenomination[1].ToString() + "#"; RetCount += Global.NoteDenomination[2].ToString() + "#"; RetCount += Global.NoteDenomination[3].ToString() + "#"; RetCount += Global.NoteDenomination[4].ToString() + "#"; RetCount += Global.NoteDenomination[5].ToString() + "#"; RetCount += Global.NoteDenomination[6].ToString(); Log.WriteEJData("ACCEPTED NOTE DETAILS ARE: " + RetCount); RDresult = RetCount; } break; case 6: { Log.WriteEJData("GET TRANSACTION CAMERA STATUS METHOD CALL"); Global.objCamera.SendMessageToCameraClient("Status"); Thread.Sleep(1000); Log.WriteEJData("TRANSACTION CAMERA STATUS IS: " + Global.objCamera.getStatus()); RDresult = Global.objCamera.getStatus(); } break; case 7: { Log.WriteEJData("TAKE PICTURE METHOD CALL"); Global.objCamera.SendMessageToCameraClient("0#Lipi#" + printdata); Global.IsCameraTakePicture = false; Log.WriteEJData("STAMP DATA IS: " + printdata); Int32 iCount = 0; do { iCount++; if (Global.IsCameraTakePicture) { break; } else { Thread.Sleep(1000); } } while (iCount <= 5); Log.WriteEJData("PICTURE CAPTURED WITH STAMP DATA"); string strBase64 = Global.objCamera.Img(); RDresult = strBase64; } break; case 8: { if (_pipeClient == null) { _pipeClient = new PipeClient(); } Log.WriteEJData("SCAN DOCUMENT METHOD CALL"); if (!Directory.Exists("C:\\DocImages\\")) { Directory.CreateDirectory("C:\\DocImages\\"); } string strDocPath = "C:\\DocImages\\" + printdata + ".jpg"; string strReturn = _pipeClient.Send("2" + "#" + strDocPath, "DocScannerRequestResponse", 1000); Log.WriteLog("Start Scan - " + strReturn, "Scanner"); Log.WriteEJData("DOCUMENT SCANNING STARTED"); if (strReturn == "success") { string base64String = null; using (System.Drawing.Image image = System.Drawing.Image.FromFile(strDocPath)) { using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); base64String = Convert.ToBase64String(imageBytes); Log.WriteLog("Image Path - " + strDocPath, "Scanner"); Log.WriteEJData("DOCUMENT SCAN SUCCESSFULLY"); RDresult = base64String; } } } else { Log.WriteEJData("DOCUMENT SCAN FAILURE"); strReturn = "Scan Failed"; RDresult = "Scan Failed"; } } break; case 9: { Log.WriteEJData("SCANNER START PREVIEW METHOD CALL"); if (_pipeClient == null) { _pipeClient = new PipeClient(); } string strData = _pipeClient.Send("1", "DocScannerRequestResponse", 1000); Log.WriteLog("Start Preview - " + strData, "Scanner"); Log.WriteEJData("DOCUMENT SCANNER PREVIEW STARTED"); RDresult = strData; } break; case 10: { Log.WriteEJData("SCANNER STOP PREVIEW METHOD CALL"); if (_pipeClient == null) { _pipeClient = new PipeClient(); } string strData = _pipeClient.Send("3", "DocScannerRequestResponse", 1000); Log.WriteLog("Stop Preview - " + strData, "Scanner"); Log.WriteEJData("DOCUMENT SCANNER PREVIEW STOPPED"); RDresult = strData; } break; case 11: { Log.WriteEJData("READ BARCODE METHOD CALL"); Global.objBarcode.DataReaded = "No Data Found"; int status = 0; if (Global.BarcodeStatus == "Barcode offline") { if (!Global.objBarcode.Initialize()) { RDresult = "Device disconnected"; status = 1; } } if (status == 0) { int iTimeOut = 0; while (true) { iTimeOut++; if (Global.objBarcode.Readbarcode() != 0) { Log.WriteEJData("BARCODE DEVICE DISCONNECTED"); Global.objBarcode.DataReaded = "Device disconnected"; Global.BarcodeStatus = "Barcode offline"; break; } if (iTimeOut == 20) { break; } Thread.Sleep(1000); if (Global.objBarcode.DataReaded != "No Data Found") { break; } } Global.objBarcode.Stopbarcode(); Log.WriteEJData("BARCODE READED SUCCESSFULLY and DATA IS: " + Global.objBarcode.DataReaded); RDresult = Global.objBarcode.DataReaded; } } break; case 12: { Log.WriteEJData("GET KIOSK ID METHOD CALL"); string mac = ""; foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus == OperationalStatus.Up && (!nic.Description.Contains("Virtual") && !nic.Description.Contains("Pseudo"))) { if (nic.GetPhysicalAddress().ToString() != "") { mac = nic.GetPhysicalAddress().ToString(); } } } Log.WriteEJData("KIOSK ID IS: " + mac); RDresult = mac; } break; case 13: //MifareReader { MifareReader obj = new MifareReader(); obj.Connect(); obj.SelectClick(); obj.Login(); RDresult = obj.ReadBlock(); if (RDresult == "") { RDresult = "No Data Found"; } } break; case 14: return("success"); break; } Global.bAppCallRunning = false; return(RDresult); } catch (Exception e) { Buffer = ""; return(e.Message); } }
public BulletAmarelo(int posX, int posY, BulletWorld f, System.Drawing.Image fig, int p) : base(posX, posY, f, fig, p) { }
public ToolStripMenuItem_Game(string label, System.Drawing.Image image, EventHandler Onclick, Game game) : base(label, image, Onclick) { this.game = game; }
private void button1_Click(object sender, EventArgs e) { //Inserts a table with 300 rows using Open Xml object bookmarkName = "bkflatOpc"; if (!this.Bookmarks.Exists("bkflatOpc")) { MessageBox.Show("Please create a bookmark with name bkflatOpc"); return; } Word.Bookmark tblBookmark = this.Bookmarks.get_Item(ref bookmarkName); if (tblBookmark.Range.Tables.Count > 0) { MessageBox.Show("Table already exists.Please delete this table."); return; } this.Application.ScreenUpdating = false; string openxml = string.Empty; int incrementor = 1; //Get existing content control id , if there is any if (this.ContentControls.Count > 0) { object index = this.ContentControls.Count; Word.ContentControl cc = this.ContentControls.get_Item(ref index); contentControlSeedId = Int32.Parse(cc.ID); contentControlSeedId = contentControlSeedId + 1; } //Get stream for the range. This is the System.IO.Packaging.Package stream Stream packageStream = this.Paragraphs[1].Range.GetPackageStreamFromRange(); //Use Open Xml SDK to process it. using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(packageStream, true)) { //Insert image to Image Part ImagePart imgPart = wordDoc.MainDocumentPart.AddImagePart(ImagePartType.Jpeg, "RImage"); System.Drawing.Image img = (System.Drawing.Image)Resources.ResourceManager.GetObject("RImage"); img.Save(imgPart.GetStream(), System.Drawing.Imaging.ImageFormat.Jpeg); //Remove all children wordDoc.MainDocumentPart.Document.Body.RemoveAllChildren(); //Generate table markup. DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table(); TableProperties properties = new TableProperties( new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }, new TableWidth() { Width = 0, Type = TableWidthUnitValues.Auto }, new TableLook() { Val = "04A0" }); table.AppendChild <TableProperties>(properties); for (int i = 0; i < 301; i++) { TableRow row = new TableRow(); for (int j = 0; j < 3; j++) { incrementor++; SdtCell contentControl = GenerateSdtCell("Sample Text", incrementor + contentControlSeedId); UInt32 value = (UInt32)(incrementor + contentControlSeedId); contentControl .Descendants <Run>() .First() .AppendChild <Drawing> (GenerateDrawing("RImage", value, "RImage.jpg", 321933L, 288000L, 19050L, 17957L, 0L, 0L)); row.AppendChild <SdtCell>(contentControl); } table.AppendChild <TableRow>(row); } int bookmarkCount = this.Bookmarks.Count; table. PrependChild <BookmarkStart>(new BookmarkStart() { Name = "bkflatOpc", Id = bookmarkCount.ToString() } ); table. AppendChild <BookmarkEnd> (new BookmarkEnd() { Id = bookmarkCount.ToString() }); wordDoc.MainDocumentPart.Document .Body .AppendChild <DocumentFormat.OpenXml.Wordprocessing.Table>(table); wordDoc.MainDocumentPart.Document.Save(); //Flush the contents of the package wordDoc.Package.Flush(); //Convert back to flat opc using this in-memory package XDocument xDoc = OpcHelper.OpcToFlatOpc(wordDoc.Package); openxml = xDoc.ToString(); } this.Application.ScreenUpdating = false; Word.Range range = FindRange("bkflatOpc"); //Insert this flat opc Xml range.InsertXML(openxml, ref missing); this.Application.ScreenUpdating = true; }
public ActionResult Create(Ponuda ponuda, int [] _UslovPrevoza) { if (ModelState.IsValid) { if (Request["_SaPDV"] != null) { if (Request["_SaPDV"].ToString().Equals("on")) { ponuda.SaPDV = true; } else { ponuda.SaPDV = false; } } else { ponuda.SaPDV = false; } if (Request["_DrugiPrevoznik"] != null) { if (Request["_DrugiPrevoznik"].ToString().Equals("on")) { ponuda.DrugiPrevoznik = true; } else { ponuda.DrugiPrevoznik = false; } } else { ponuda.DrugiPrevoznik = false; } ponuda.ZapisAktivan = true; ponuda.DatumZapisa = DateTime.Now.AddHours(7); String SB = ponuda.DatumDnevnika.Value.ToString("yyyyMMdd"); int BR = db.Ponuda.Where(c => c.SerijskiBroj.Contains(SB)).Count() + 1; ponuda.SerijskiBroj = SB + "-" + BR; ponuda.GostPristup = RandomString(25); db.Ponuda.Add(ponuda); db.SaveChanges(); using (System.Drawing.Image imagen = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.CodeQr).Draw(AppSettings.GetSettings()["domain_name"] + "/Ponuda/ReportPonuda2/" + ponuda.IdDnevnik, 50, 2)) { String path = Server.MapPath("~/BARCODE/" + ponuda.SerijskiBroj + ".png"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } imagen.Save(path, System.Drawing.Imaging.ImageFormat.Png); } List <PonudaUsloviPrevoza> lpu = new List <PonudaUsloviPrevoza>(); foreach (int i in _UslovPrevoza) { db.PonudaUsloviPrevoza.Add((new PonudaUsloviPrevoza { IdPonuda = ponuda.IdDnevnik, IdUsloviPrevoza = i })); } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(ponuda)); }
/// <summary> /// 模板导出Excel /// 可分页导出. /// </summary> /// <param name="sheetname">sheetname</param> /// <param name="startrow">startrow</param> /// <param name="rows">rows</param> /// <param name="cols">cols</param> /// <param name="copies">copies</param> /// <param name="returnfile">returnfile</param> public static void ExportByTemplate(IList <modExcelRangeData> list, string sheetname, int startrow, int rows, int cols, int copies) { try { if (list == null || list.Count == 0) { MessageBox.Show(clsTranslate.TranslateString("No data!"), clsTranslate.TranslateString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string filename; #if DEBUG filename = @"C:\HongBiao\templates.xls"; #else filename = clsLxms.GetParameterValue("EXCEL_TEMPLETE_FILE"); #endif if (!File.Exists(filename)) { MessageBox.Show(clsTranslate.TranslateString("Can not find the templete file") + ": \r\n" + filename, clsTranslate.TranslateString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string destfile = GetExportFilePath(0); if (File.Exists(destfile)) { File.Delete(destfile); } Util.retValue1 = destfile; File.Copy(filename, destfile); Excel.Application m_objExcel = new Excel.Application(); m_objExcel.DisplayAlerts = false; Excel.Workbooks m_objBooks = m_objExcel.Workbooks; m_objBooks.Open(destfile, 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); Excel.Workbook m_objBook = (Excel.Workbook)m_objBooks.get_Item(1); Excel.Sheets sm_objSheets = (Excel.Sheets)m_objBook.Worksheets; Excel.Worksheet m_objSheet = (Excel.Worksheet)sm_objSheets.get_Item(sheetname); for (int i = sm_objSheets.Count; i >= 1; i--) { Excel.Worksheet m_Sheet = sm_objSheets.get_Item(i); if (m_Sheet.Name.ToLower().CompareTo(sheetname.ToLower()) != 0) { m_Sheet.Delete(); } } //Excel.Range templaterange = m_objSheet.Range(m_objSheet.Cells[startrow, 1], m_objSheet.Cells[startrow + rows - 1, cols]); Excel.Range templaterange = m_objSheet.Range[m_objSheet.Cells[startrow, 1], m_objSheet.Cells[startrow + rows - 1, cols]]; for (int i = 1; i < copies; i++) { Excel.Range targetrange = (Excel.Range)m_objSheet.Range[m_objSheet.Cells[rows * i + 1, 1], m_objSheet.Cells[rows * (i + 1), cols]]; templaterange.Copy(targetrange); for (int k = 0; k < rows; k++) { m_objSheet.Rows[rows * i + 1 + k].RowHeight = m_objSheet.Rows[startrow + k].RowHeight; } } Excel.Range range; foreach (modExcelRangeData mod in list) { range = (Excel.Range)m_objSheet.get_Range(mod.CellBegin, mod.CellEnd); if (!mod.Is_Pic) { range.Value = mod.CellValue; } else { if (!string.IsNullOrEmpty(mod.CellValue) && File.Exists(mod.CellValue)) { System.Drawing.Image im = System.Drawing.Image.FromFile(mod.CellValue); double iLeft = range.Left + 1; double iTop = range.Top + 1; double iWidth = range.Width - 2; double iHeight = range.Height - 2; if (im.Width <= range.Width) { iWidth = im.Width; iLeft = range.Left + (range.Width - im.Width) / 2; } if (im.Height <= range.Height) { iHeight = im.Height; iTop = range.Top + (range.Height - im.Height) / 2; } im.Dispose(); m_objSheet.Activate(); range.Select(); m_objSheet.Shapes.AddPicture(mod.CellValue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, (float)iLeft, (float)iTop, (float)iWidth, (float)iHeight); } } } m_objSheet.Activate(); System.Windows.Forms.Application.DoEvents(); m_objExcel.DisplayAlerts = false; m_objExcel.AlertBeforeOverwriting = false; //保存工作簿 m_objExcel.Visible = true; return; } catch (System.Exception ex) { MessageBox.Show(ex.Message, clsTranslate.TranslateString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } }
private static void BackgroundRenderImages_BACKGROUND(FlowDocument flow_document, List <AnnotationWorkGenerator.AnnotationWork> annotation_works, AnnotationReportOptions annotation_report_options) { WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread(); ShutdownableManager.Sleep(annotation_report_options.InitialRenderDelayMilliseconds); PDFDocument last_pdf_document = null; StatusManager.Instance.ClearCancelled("AnnotationReportBackground"); for (int j = 0; j < annotation_works.Count; ++j) { if (ShutdownableManager.Instance.IsShuttingDown) { Logging.Error("Canceling creation of Annotation Report due to signaled application shutdown"); StatusManager.Instance.SetCancelled("AnnotationReportBackground"); } StatusManager.Instance.UpdateStatus("AnnotationReportBackground", "Building annotation report image", j, annotation_works.Count, true); if (StatusManager.Instance.IsCancelled("AnnotationReportBackground")) { Logging.Warn("User canceled annotation report generation"); break; } AnnotationWorkGenerator.AnnotationWork annotation_work = annotation_works[j]; PDFDocument pdf_document = annotation_work.pdf_document; // Clear down our previously caches pages if (null != last_pdf_document && last_pdf_document != pdf_document) { if (last_pdf_document.DocumentExists) { last_pdf_document.FlushCachedPageRenderings(); } } // Remember this PDF document so we can flush it if necessary last_pdf_document = pdf_document; // Now render each image PDFAnnotation pdf_annotation = annotation_work.pdf_annotation; if (null != pdf_annotation) { try { // Clear the waiting for processing text WPFDoEvents.InvokeAsyncInUIThread(() => { annotation_work.processing_error.Text = ""; }); if (pdf_document.DocumentExists) { // Fill in the paragraph text if (null != annotation_work.annotation_paragraph) { WPFDoEvents.InvokeAsyncInUIThread(() => { BuildAnnotationWork_FillAnnotationText(pdf_document, pdf_annotation, annotation_work); }); } if (null != annotation_work.report_floater) { try { System.Drawing.Image annotation_image = PDFAnnotationToImageRenderer.RenderAnnotation(pdf_document, pdf_annotation, 80); BitmapSource cropped_image_page = BitmapImageTools.FromImage(annotation_image); WPFDoEvents.InvokeAsyncInUIThread(() => { annotation_work.report_image.Source = cropped_image_page; annotation_work.report_floater.Width = new FigureLength(cropped_image_page.PixelWidth / 1); }); } catch (Exception ex) { Logging.Warn(ex, "There was a problem while rendering an annotation."); WPFDoEvents.InvokeAsyncInUIThread(() => { annotation_work.report_image.Source = Icons.GetAppIcon(Icons.AnnotationReportImageError); annotation_work.processing_error.Text = "There was a problem while rendering this annotation."; }); } } } else { WPFDoEvents.InvokeAsyncInUIThread(() => { if (null != annotation_work.report_image) { annotation_work.report_image.Source = Icons.GetAppIcon(Icons.AnnotationReportImageError); } annotation_work.processing_error.Text = "Can't show image: The PDF does not exist locally."; }); } } catch (Exception ex) { Logging.Error(ex, "There was an error while rendering page {0} for document {1} for the annotation report", pdf_annotation.Page, pdf_annotation.DocumentFingerprint); WPFDoEvents.InvokeAsyncInUIThread(() => { if (null != annotation_work.report_image) { annotation_work.report_image.Source = Icons.GetAppIcon(Icons.AnnotationReportImageError); } annotation_work.processing_error.Text = "Can't show image: There was an error rendering the metadata image."; }); } } } // And flush the rendering cache of the last document if (null != last_pdf_document) { if (last_pdf_document.DocumentExists) { last_pdf_document.FlushCachedPageRenderings(); } } StatusManager.Instance.ClearStatus("AnnotationReportBackground"); }
private void ProcessNewsContent() { NewsContent st = null; if (NewsId > 0) { st = db.NewsContents.SingleOrDefault <NewsContent>(s => s.Id == NewsId && s.ApprovementStatus == (short)EnumNewsApprovementStatus.ChuaDuyet); } if (st == null) { return; } PreventSQLInjection.ClearSQLInjectionInAllControls(this); st.NewsTitle = txtTieuDe.Text; st.Description = txtMoTa.Text; //st.Content = Editor1.MainEditor.Content; st.Content = Editor1.MainEditor.Text; st.LastUpdatedTime = DateTime.Now; st.CategoryId = Convert.ToInt32(rcbCategories.SelectedValue); //st.Hidden = !ckbShow.Checked; //upload hinh dai dien cua ban tin if (fulHinhAnh.HasFile) { //kiem tra kieu va kich co file //if ((NT.Lib.Globals.IsImageFile(fulHinhAnh.FileName)) && (fulHinhAnh.FileContent.Length <= SystemConfig.ApplicationConfig.MaxUserImageSizeUpload)) if (NT.Lib.Globals.IsImageFile(fulHinhAnh.FileName)) { //xoa anh cu neu co (truong hop cap nhat) if (!String.IsNullOrEmpty(st.ImagePath)) { System.IO.File.Delete(Server.MapPath(st.ImagePath)); } string uploadFolder = Server.MapPath(virtualUploadFolder + ThumbFolder); if (!System.IO.Directory.Exists(uploadFolder)) { System.IO.Directory.CreateDirectory(uploadFolder); } //tao chuoi ten file ngau nhien string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Hash.GetRandomHashKey(4) + "." + NT.Lib.Globals.GetFileExtension(fulHinhAnh.FileName); //resize anh System.Drawing.Image img = System.Drawing.Image.FromStream(fulHinhAnh.PostedFile.InputStream); System.Drawing.Image imgResized = Utilities.ResizeImage(img, SystemConfig.ApplicationConfig.News_MaxImageWidth, SystemConfig.ApplicationConfig.News_MaxImageWidth); imgResized.Save(uploadFolder + fileName);//luu file vao o cung //luu duong dan anh vao db st.ImagePath = virtualUploadFolder + ThumbFolder + fileName; } } NewsApprovementHistory apHis = new NewsApprovementHistory(); apHis.NewsId = st.Id; if (ddlApprove.SelectedValue == "1") { st.ApprovementStatus = (short)EnumNewsApprovementStatus.DaDuyetChuaXuatBan; apHis.IsApproved = true; } else { st.ApprovementStatus = (short)EnumNewsApprovementStatus.KhongDuyet; apHis.IsApproved = false; } apHis.AppStatustId = st.ApprovementStatus; apHis.ApprovedBy = UserInfo.UserAccount.AccountName; apHis.Comment = txtApprovementDetail.Text; apHis.CreatedTime = DateTime.Now; NewsApprovementHistory nah = db.NewsApprovementHistories.OrderByDescending <NewsApprovementHistory, DateTime>(nn => nn.CreatedTime.Value).FirstOrDefault <NewsApprovementHistory>(nnn => nnn.NewsId == st.Id); //Int16 lastSeq = (from na in db.NewsApprovementHistories where na.NewsId == st.Id orderby na.CreatedTime descending select na.Sequence.Value).Take(1).SingleOrDefault<Int16>(); short lastSeq = 0; if (nah != null && nah.Sequence.HasValue) { lastSeq = nah.Sequence.Value; } apHis.Sequence = (short)(lastSeq + 1); //auto publish news //st.ApprovementStatus = (short)EnumNewsApprovementStatus.DaXuatBan; //st.ShowInDropdownMenu = true; //st.ShowInFeature = ckbFeature.Checked; //st.ShowInMostView = true; //st.ShowInNewest = ckbNewest.Checked; //st.Hidden = false; //st.PublishFrom = DateTime.Now; //st.PublishTo = DateTime.MaxValue; //if (!IsInUpdateMode) //{ // //st.StoreId = StoreId; // st.CreatedTime = st.LastUpdatedTime; // st.UserId = UserId; // db.NewsContents.InsertOnSubmit(st); //} db.NewsApprovementHistories.InsertOnSubmit(apHis); db.SubmitChanges(); //NT.Lib.Utilities.ClearAllInputControls(pnlAddNew.Controls); //ChangeMode(false); Response.Redirect(Common.GenerateAdminUrl("approvenews")); }
public static byte[] PerformOCRTesseract(byte[] image) { // Specify that Tesseract use three 3 languages: English, Russian and Vietnamese. //string tesseractLanguages = "rus+eng+vie"; string tesseractLanguages = "eng"; // A path to a folder which contains languages data files and font file "pdf.ttf". // Language data files can be found here: // Good and fast: https://github.com/tesseract-ocr/tessdata_fast // or // Best and slow: https://github.com/tesseract-ocr/tessdata_best // Also this folder must have write permissions. string tesseractData = Path.GetFullPath(@"..\..\tessdata\"); // A path for a temporary PDF file (because Tesseract returns OCR result as PDF document) string tempFile = Path.Combine(tesseractData, Path.GetRandomFileName()); bool skipImages = true; try { using (Tesseract.IResultRenderer renderer = Tesseract.PdfResultRenderer.CreatePdfRenderer(tempFile, tesseractData, skipImages)) { using (renderer.BeginDocument("Serachablepdf")) { using (Tesseract.TesseractEngine engine = new Tesseract.TesseractEngine(tesseractData, tesseractLanguages, Tesseract.EngineMode.Default)) { engine.DefaultPageSegMode = Tesseract.PageSegMode.Auto; using (MemoryStream msImg = new MemoryStream(image)) { System.Drawing.Image imgWithText = System.Drawing.Image.FromStream(msImg); for (int i = 0; i < imgWithText.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); i++) { imgWithText.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i); using (MemoryStream ms = new MemoryStream()) { imgWithText.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] imgBytes = ms.ToArray(); using (Tesseract.Pix img = Tesseract.Pix.LoadFromMemory(imgBytes)) { using (var page = engine.Process(img, "Serachablepdf")) { renderer.AddPage(page); } } } } } } } } return(File.ReadAllBytes(tempFile + ".pdf")); } catch (Exception e) { Console.WriteLine(); Console.WriteLine("Please be sure that you have Language data files (*.traineddata) in your folder \"tessdata\""); Console.WriteLine("The Language data files can be download from here: https://github.com/tesseract-ocr/tessdata_fast"); Console.ReadKey(); throw new Exception("Error Tesseract: " + e.Message); } finally { if (File.Exists(tempFile + ".pdf")) { File.Delete(tempFile + ".pdf"); } } }
internal static string CreateThumbnail(string strImage) { var imageFileName = Path.GetFileName(strImage); if (string.IsNullOrEmpty(imageFileName) || imageFileName.StartsWith("thumbnail_")) { strImage = Globals.ApplicationPath + "/" + strImage.Substring(strImage.IndexOf("portals\\")); strImage = strImage.Replace("\\", "/"); return(strImage); } var strThumbnail = strImage.Replace(Path.GetFileName(strImage), "thumbnail_" + imageFileName); if (NeedCreateThumbnail(strThumbnail, strImage)) { lock (_threadLocker) { if (NeedCreateThumbnail(strThumbnail, strImage)) { const int intSize = 150; //size of the thumbnail try { var objImage = Image.FromFile(strImage); //scale the image to prevent distortion int intHeight; int intWidth; double dblScale; if (objImage.Height > objImage.Width) { //The height was larger, so scale the width dblScale = (double)intSize / objImage.Height; intHeight = intSize; intWidth = Convert.ToInt32(objImage.Width * dblScale); } else { //The width was larger, so scale the height dblScale = (double)intSize / objImage.Width; intWidth = intSize; intHeight = Convert.ToInt32(objImage.Height * dblScale); } //create the thumbnail image var objThumbnail = objImage.GetThumbnailImage(intWidth, intHeight, null, IntPtr.Zero); //delete the old file ( if it exists ) if (File.Exists(strThumbnail)) { File.Delete(strThumbnail); } //save the thumbnail image objThumbnail.Save(strThumbnail, objImage.RawFormat); //set the file attributes File.SetAttributes(strThumbnail, FileAttributes.Normal); File.SetLastWriteTime(strThumbnail, File.GetLastWriteTime(strImage)); //tidy up objImage.Dispose(); objThumbnail.Dispose(); } catch (Exception ex) //problem creating thumbnail { Logger.Error(ex); } } } } strThumbnail = Globals.ApplicationPath + "/" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\")); strThumbnail = strThumbnail.Replace("\\", "/"); //return thumbnail filename return(strThumbnail); }
public Car(string year, string make, string model, string color, System.Drawing.Image image) { // TODO: Complete member initialization this.year = year; this.make = make; this.model = model; this.color = color; this.image = image; String[] makes = this.make.Split(); String[] models = this.model.Split(); String[] colors = this.color.Split(); this.query = this.year + "+"; foreach (String item in makes) { this.query += item + "+"; } foreach (String item in models) { this.query += item + "+"; } }