image management code? - asp.net

two days back i ask a question for image management, i get some reference that is 4guys
the code is working fine i want to store that manged image in a folder but i not understand how can i save, can u help me. this is my code.....
public partial class Default2 : System.Web.UI.Page
{
public bool ThumbnailCallback()
{
return false;
}
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = default(System.Drawing.Image.GetThumbnailImageAbort);
dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image fullSizeImg = default(System.Drawing.Image);
fullSizeImg = System.Drawing.Image.FromFile("C:\\05.jpg");
System.Drawing.Image thumbNailImg = default(System.Drawing.Image);
thumbNailImg = fullSizeImg.GetThumbnailImage(100, 100, dummyCallBack, IntPtr.Zero);
}
}

To save an image to a folder on the server, call image.Save(path).
EDIT: You can send a smaller version of an image to the browser like this:
using(Image originalImage = something)
using(Bitmap smallImage = new Bitmap(originalImage, width, height)) {
Stream stream = new MemoryStream();
smallImage.Save(stream);
Response.OutputStream.Write(stream.ToArray(), 0, stream.Length);
}

Related

What is the Most simple way to store image in Data base in MVC

ok, So criticism apart, I'm New to MVC, my Point is how can i store an image in data base that will be uploaded by user.
i'm Creating a simple blog via MVC And what i Want is A form Same like WordPress "ADD NEW POST". Where user can enter title,TAGS,Headings, But What my Part is, I have to store all of them in DB. i can Do the CSS part, but i'm struck in Functionality that will be Getting all values From user (view) And Then Storing it in database also Displaying it.
below is my google-d Code for View in MVC.
#model SimpleBlogg.Models.PostContent
#{
ViewBag.Title = "AddContentToDB";
}
<div class="UploadPicForm" style="margin-top:20px;">
#using (Html.BeginForm("AddContentToDB", "AddNewPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}
</div>
Save as Base64 string:
static string base64String = null;
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
public System.Drawing.Image Base64ToImage()
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
protected void ImageToBase_Click(object sender, EventArgs e)
{
TextBox1.Text = ImageToBase64();
}
protected void BaseToImage_Click(object sender, EventArgs e)
{
Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));
Image1.ImageUrl = "~/Images/Hello.jpg";
}
source: http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64-string-to-image

drop-down list in C# issue

drop-down list in C#.net not showing the items it supposed to show!
i hv a drop-down list that suppose to show image names from a folder, but it is not doing that!
i dont have errors when launching the .aspx file!
buuuuuut when i get output there is only empty dropdown list!
this the ManageProducts.aspx codes are:
Name:
Type:
" SelectCommand="SELECT * FROM [ProductTypes] ORDER BY [Name]">
Price:
Image:
Description:
and this the behind codes:
using System;
using System.Collections;
using System.IO;
public partial class PagesNew_ManagementPages_ManageProducts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //this baby makes the data not come every time the pg is refreshed ,
//postback=refresh page
GetImages();
}
private void GetImages()
{
try
{
//get all filepaths
string[] images = Directory.GetFiles(Server.MapPath("~/Img/Products/"));
//get all filenames and put them in a stupid array....yeah DSA days
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(#"\", StringComparison.Ordinal) + 1);
imageList.Add(imageName);
// see the Array in dd viwe datasource and refresh
ddImage.AppendDataBoundItems = true;
ddImage.DataBind();
}
}
catch (Exception e)
{
lblResult.Text = e.ToString();
}
}
protected void ddImage_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You want to bind your datalist outside of the for loop.
ArrayList imageList = new ArrayList();
foreach (string image in images)
{
string imageName = image.Substring(image.LastIndexOf(#"\", StringComparison.Ordinal) + 1);
imageList.Add(imageName);
}
ddImage.DataSource = imageList;
ddImage.AppendDataBoundItems = true;
ddImage.DataBind();

user control properties

i have a detail view with below markup and data source of this detail view is from stored procedure "spDocResult" like below:
select DocId,TransId,FileId,Filename,ContentType,Data,DocumentNo,Title,TRANSMITTAL
from DocumentSum2
where (DocId=#Docid)AND(Transid=#Transid)
one field of this detail view should be show Efile Names so i have made 1 user control for that
public partial class FileTemp : System.Web.UI.UserControl
{
private EDMSDataContext _DataContext;
private IEnumerable<tblFile> _Efiles;
public IEnumerable<tblFile> Efiles
{
set { _Efiles = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Download")
{
_DataContext = new EDMSDataContext();
//you can get your command argument values as follows
string FileId = e.CommandArgument.ToString();
int _FileId = Convert.ToInt32(FileId);
tblFile Efile = (from ef in _DataContext.tblFiles
where ef.FileId == _FileId
select ef).Single();
if (Efile != null)
{
download(Efile);
}}}
private void download ( tblFile Efile)
{
Byte[] bytes = (Byte[])Efile.Data.ToArray();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = Efile.ContentType.ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ Efile.FileName.ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
public override void DataBind()
{
base.DataBind();
GridViewEfile.DataSource = _Efiles;
GridViewEfile.DataBind();
}
}
now i have problem because datasource of detailview comes from a stored procedure and properties of user control is from tblFile, so when i use DetailsView1_DataBound i do not know how i have to get user control properties.when i use below code, i have error
can not implicity convert type string to system.collection.generic.iEnumerable<tblfile>
i have error for this line
fileList.Efiles = docresult.Filename;
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
spDocResultResult docresult = (spDocResultResult)DetailsView1.DataItem;
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
fileList.Efiles = docresult.Filename;
fileList.DataBind();
}
This might not be a data binding issue at all. It's a little hard to gather from the context, but...
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
fileList.Efiles = docresult.Filename;
Is fileList.Efiles a list of items that you just want to assign a file name to? If so, you might just need to foreach through them.
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
Also, add this line to your Efiles declaration to solve the Get accessor error.
public IEnumerable<tblFile> Efiles
{
get { return _Efiles; } // <- here
set { _Efiles = value; }
}

Selenium-RC loading empty frame

As stated above, I am running out an automated test on a website.
I am use selenium RC to do that but I'm just not sure why I am unable to open the website (actually i did open it), but its content is not showing.
There are just a few empty frame boxes.
This originally had too much code so I'm adding some more.
Anyone know why? Thank you.
Here is my code (unrelated code removed):
private ISelenium selenium;
private StringBuilder verificationErrors;
private Process worKer = new Process();
private string
serverHost = "localhost",
browserString = #"*iexploreproxy",
startUpURL = "";
private int
portNumber = 4444;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "CNY")
{
startUpURL = "http://malaysia.yahoo.com/";
}
}
private void btnStartServer_Click(object sender, EventArgs e)
{
worKer.StartInfo.FileName = #"C:\LjT\SeleniumServer.bat";
worKer.Start();
}
private void WakeUpSElenium()
{
selenium = new DefaultSelenium(serverHost, portNumber, browserString, startUpURL);
selenium.Start();
verificationErrors = new StringBuilder();
}
private void ToDoList()
{
selenium.Open("/");
//selenium.SelectFrame("iframe_content");
selenium.Type("id=txtFirstName", "1");
selenium.Click("id=rbtnGender_0");
}
private void btnTest_Click(object sender, EventArgs e)
{
try
{
WakeUpSElenium();
ToDoList();
}
catch
{}
}
You are not navigating anywhere, i.e this code here, will not navigate to any page at all:
selenium.Open("/");
I assume you meant to make it this:
selenium.Open(startUpURL); // this is the value from the combobox.

how to use FileSystemWatcher using asp.net(C#)

SENARIO: i have few folders on my FTP server, belongs to particular user. Suppose i have 10GB total space and i assign 1GB to each user i.e can accomodate 10 users having 1GB each.
now users can add/delete/edit any type of file to utilize the storage space. All i need to do is to restrict users not to exceed 1gb space for their file storage. For this i want to use FileSystemWatcher to notify me that a user had created/deleted/edited a file so that i can minimize the space from 1gb incase of creation of a file or add a space incase of deletion.
this is the piece of coding using FSW. when user gets loged-in with proper id and password, respective folder is opened (present at FTP server) where he can add/delete/edit any type of file and according to that i hav to monitor d space ulitilized by him.
but d problem is the event handlers (written in console). i dont understand what happens when this code is being runned... i dontknow how to use FSW class so that i can monitor d changes user is making in his folder.
please help ... THANX
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class _Default: System.Web.UI.Page {
public class ClsFileSystemWatcher {
public static void OnChanged(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnDeleted(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnCreated(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnRenamed(object source, RenamedEventArgs e) {
Console.WriteLine("File "+e.OldFullPath+" [Changed to] "+e.FullPath);
}
public static void OnError(object source, ErrorEventArgs e) {
Console.WriteLine("Error "+e);
}
public void FileWatcher(string InputDir) {
using (FileSystemWatcher fsw = new FileSystemWatcher()) {
fsw.Path = InputDir;
fsw.Filter = #"*";
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName|NotifyFilters.Attributes|NotifyFilters.LastAccess|NotifyFilters.LastWrite|NotifyFilters.Security|NotifyFilters.Size|NotifyFilters.CreationTime|NotifyFilters.DirectoryName;
fsw.Changed += OnChanged;
fsw.Created += OnCreated;
fsw.Deleted += OnDeleted;
fsw.Renamed += OnRenamed;
fsw.Error += OnError;
fsw.EnableRaisingEvents = true;
//string strOldFile = InputDir + "OldFile.txt";
//string strNewFile = InputDir + "CreatedFile.txt";
//// Making changes in existing file
//using (FileStream stream = File.Open(strOldFile, FileMode.Append))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Appending new line in Old File");
// sw.Flush();
// sw.Close();
//}
//// Writing new file on FileSystem
//using (FileStream stream = File.Create(strNewFile))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Writing First line into the File");
// sw.Flush();
// sw.Close();
//}
//File.Delete(strOldFile);
//File.Delete(strNewFile);
// Minimum time given to event handler to track new events raised by the filesystem.
Thread.Sleep(1000);
}
}
}
private DAL conn;
private string connection;
private string id = string.Empty;
protected void Page_Load(object sender, EventArgs e) {
connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\project\\Desktop\\BE prj\\dbsan.mdb;Persist Security Info=False";
conn = new DAL(connection);
////*** Opening Respective Folder of a User ***////
DirectoryInfo directories = new DirectoryInfo(#"C:\\Inetpub\\ftproot\\san\\");
DirectoryInfo[] folderList = directories.GetDirectories();
if (Request.QueryString["id"] != null) {
id = Request.QueryString["id"];
}
string path = Path.Combine(#"C:\\Inetpub\\ftproot\\san\\", id);
int folder_count = folderList.Length;
for (int j = 0; j < folder_count; j++) {
if (Convert.ToString(folderList[j]) == id) {
Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
}
}
ClsFileSystemWatcher FSysWatcher = new ClsFileSystemWatcher();
FSysWatcher.FileWatcher(path);
}
}
Each time you reload the page you create new FSW - in that case you won't get any events raised, because from the point of newly created FSW nothing was changes. Try to preserve your FileSystemWatcher object in the Session state.
So flow would look like:
User logs in – you create FSW and preserve it in Session
User reloads the page – get FSW from Session (do not create new one)
You should create a worker role (service) for this type of thing. I think it is not appropriate to have something like this inside of a page.

Resources