Snitz Forums 2000
Snitz Forums 2000
Home | Profile | Register | Active Topics | Members | Search | FAQ
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 Community Forums
 Code Support: ASP.NET (Non-Forum Related)
 C# Help - Database Insert & RegEx
 New Topic  Topic Locked
 Printer Friendly
Next Page
Author Previous Topic Topic Next Topic
Page: of 3

dayve
Forum Moderator

USA
5820 Posts

Posted - 25 November 2004 :  23:57:45  Show Profile  Visit dayve's Homepage
My patience level is at an all time low and so is my C# experience. I guess I just want to do things fast, but that does not appear as if it is going to happen, so off to Snitz and other coding forums I go...

I have a script I found and in the process of modifying for uploading an image and creating thumbnails in 3 formats, .jpg, .gif and .png.

Problem # 1:
I can't seem to figure out how to do a LCase or even an IgnoreCase when viewing a filename.

Problem # 2:
I need to take the results of variables and form values and insert them into a database.

The working code I am providing is in an extremely premature stage, but if I can get by these 2 challenges, I would be very relieved.


<%@ Page Language="C#" %>
<%@ import namespace="System.IO" %>
<%@ import Namespace="System.Drawing.Imaging" %>
<%@ import Namespace="System.Drawing" %>

<script runat="server">
  void UploadBut_Click(Object sender, EventArgs args)
  {
  	   DateTime MyDate = DateTime.Now; 	   
	   String UploadedFile = PhotoUpload.PostedFile.FileName;	
	   String FilePath = Request.PhysicalApplicationPath + "\\files\\";	
	   
	   int ExtractPos =	UploadedFile.LastIndexOf("\\") + 1;	 
	   String UploadedFileName =  MyDate.ToString("ddMMyyhhmmss") + "_" + UploadedFile.Substring(ExtractPos,UploadedFile.Length - ExtractPos);
	   
       PhotoUpload.PostedFile.SaveAs(FilePath + UploadedFileName );
	   
      String ImageName = "thumb_" + UploadedFileName;

	  	ImageName = Regex.Replace(ImageName, ".jpg", "");
		ImageName = Regex.Replace(ImageName, ".gif", "");
		ImageName = Regex.Replace(ImageName, ".jpeg", "");
		ImageName = Regex.Replace(ImageName, ".png", "");
	  	ImageName = Regex.Replace(ImageName, ".JPG", ""); // Should not have to do this!
		ImageName = Regex.Replace(ImageName, ".GIF", ""); // Need to figure out LCase in C#
		ImageName = Regex.Replace(ImageName, ".JPEG", ""); // OR need to IgnoreCase
		ImageName = Regex.Replace(ImageName, ".PNG", ""); // For now this will do.

      Int32 ImageWidth = 125;
      Stream ImageStream = PhotoUpload.PostedFile.InputStream;
    
      if ( PhotoUpload.PostedFile.FileName != "") 
      {
        SaveUploadImageAsJpeg(ImageStream, FilePath, ImageName, ImageWidth);
        SaveUploadImageAsGif(ImageStream, FilePath, ImageName, ImageWidth);
        SaveUploadImageAsPng(ImageStream, FilePath, ImageName, ImageWidth);
      }
  }

  void SaveUploadImageAsJpeg(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth)
  {        
      String Extension = ".jpg";
      String MimeType = "image/jpeg";
      long Quality = 95;
      UploadImage(ImageStream, FilePath, ImageName, ImageWidth, Extension, MimeType, Quality);
  }

  void SaveUploadImageAsGif(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth)
  {            
      String Extension = ".gif";
      String MimeType = "image/gif";
      long Quality = 100;
      UploadImage(ImageStream, FilePath, ImageName, ImageWidth, Extension, MimeType, Quality);
  }

  void SaveUploadImageAsPng(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth)
  {            
      String Extension = ".png";
      String MimeType = "image/png";
      long Quality = 0; // has no effect on png files
      UploadImage(ImageStream, FilePath, ImageName, ImageWidth, Extension, MimeType, Quality);
  }    

  void UploadImage(Stream ImageStream, String FilePath, String ImageName, Int32 ImageWidth, String Extension, String MimeType, long Quality )
  {            
      try
      {                
          System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(ImageStream);
      
          Int32 old_height = UploadedImage.Height;
          Int32 old_width = UploadedImage.Width;
      
          Int32 new_width  = ImageWidth; 
          Int32 new_height = (Int32) Math.Ceiling( (old_height * new_width)/old_width );
      
          Bitmap smallerImg = new Bitmap(new_width, new_height);    
          Graphics g = Graphics.FromImage(smallerImg);
          g.DrawImage(UploadedImage, 0, 0, new_width, new_height);
      
          UploadedImage.Dispose();
      
          if ( !Extension.Equals(".png") )
          {
              EncoderParameters myParams = new EncoderParameters(1);
              myParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality );                
              smallerImg.Save( FilePath + ImageName + Extension, GetEncoderInfo(MimeType), myParams);        
          }
          else
          {
              smallerImg.Save(  FilePath + ImageName + Extension , ImageFormat.Png);                    
          }
          smallerImg.Dispose();        
      }
      finally {  }
  }
      
  private ImageCodecInfo GetEncoderInfo(string mimeType)
  {
      int j;
      ImageCodecInfo[] encoders;
      encoders = ImageCodecInfo.GetImageEncoders();
      for(j = 0; j < encoders.Length; ++j)
      {
          if(encoders[j].MimeType == mimeType)
          {
              return encoders[j];
          }
      }
      return null;
  }

  // Validate the uploaded file is an image (.jpg, .jpeg, .gif)
  void ValidatePicture(Object src, ServerValidateEventArgs args)
  {                
      args.IsValid = false;
      String fileName = PhotoUpload.PostedFile.FileName.ToLower();
      if (fileName == "" || (fileName.IndexOf(".jpg") > -1) || (fileName.IndexOf(".jpeg") > -1) || (fileName.IndexOf(".gif") > -1)) args.IsValid = true;
  }  
  
</script>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <title></title>
</head>

<body>
<form id="MainForm" enctype="multipart/form-data" runat="server">
  <table cellpadding="4" cellspacing="0" border="0">
      <tr><td colspan="2" height="5"></td></tr>
      <tr>
          <td valign="top">Photo:</td>
          <td> 
            <input id="PhotoUpload" runat="server" type="File" class="formcopy" />
            <asp:customvalidator enableclientscript="false" cssclass="formcopy" display="dynamic" runat="server" text="* must be a .jpg, .jpeg, or .gif" controlToValidate="PhotoUpload" onservervalidate="ValidatePicture" />
          </td>
      </tr>
  </table>                    
  <br />
  <table cellpadding="4" cellspacing="0" border="0">
      <tr>
          <td><asp:button ID="AddSaveButton" text="Upload" onclick="UploadBut_Click" cssclass="formcopy" runat="server" /></td>
          <td></td>
      </tr>
  </table>
</form>
</body>
</html>


Edited by - dayve on 26 November 2004 00:06:27

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  16:33:37  Show Profile  Visit dayve's Homepage
okay I'll settle for some really good C# reference sites then.

Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  18:34:40  Show Profile  Send ruirib a Yahoo! Message
Regarding the case issue, you just need to use the RegexOptions enumeration to the IgnoreCase flag, like this:

RegexOptions.IgnoreCase

Do this before your replace and you are set.
Can't help with the 2nd problem now :). What is the issue, the DB insertion?


Snitz 3.4 Readme | Like the support? Support Snitz too

Edited by - ruirib on 26 November 2004 18:38:26
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  18:37:26  Show Profile  Visit dayve's Homepage
yeah, I did the RegexOptions.IgnoreCase but it bombed out...

Compiler Error Message: CS0118: 'System.Text.RegularExpressions.RegexOptions.IgnoreCase' denotes a 'field' where a 'class' was expected

Line 17:
Line 18: String ImageName = "thumb_" + UploadedFileName;
Line 19: RegexOptions.IgnoreCase
Line 20: ImageName = Regex.Replace(ImageName, ".jpg", "");
Line 21: ImageName = Regex.Replace(ImageName, ".gif", "");

quote:
Can't help with the 2nd problem now :). What is the issue, the DB insertion?

yes.


Edited by - dayve on 26 November 2004 18:39:33
Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  18:45:44  Show Profile  Send ruirib a Yahoo! Message
Try this:

ImageName = Regex.Replace(ImageName, ".jpg", "", RegexOptions.IgnoreCase);


Snitz 3.4 Readme | Like the support? Support Snitz too

Edited by - ruirib on 26 November 2004 18:46:28
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  18:48:20  Show Profile  Visit dayve's Homepage
thanks.. that worked.

Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  18:52:34  Show Profile  Send ruirib a Yahoo! Message
Ok, so what don't you know, the whole thing, establishing a connection and executing an SQL statement, or just the latter?


Snitz 3.4 Readme | Like the support? Support Snitz too
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  18:57:20  Show Profile  Visit dayve's Homepage
I find bits and pieces of how to use ADO in a C# environment but being that C# is so strict, I tend to bomb out my inserts quite easily. I have no problems doing this with VB.NET though.

Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  19:07:49  Show Profile  Send ruirib a Yahoo! Message
Regarding the database updating, something along these lines should do it

using System;
using System.Data;
using System.Data.SqlClient;

class SnitzExample
{
    public static void Main()
    {
       SqlConnection sCon = new SqlConnection("Initial Catalog=MyDB;Data Source=localhost;Integrated Security=SSPI;");
       SqlCommand sCmd = new SqlCommand("Your Query goes here", sCon); // build the SQL there and create the command

       sCon.Open();

       sCmd.ExecuteNonQuery();  //This will execute the append query

       sCon.Close();
    }
}

Of course, details of the conn string can vary just as in ADO, but you can use a valid conn string just as if it was for Snitz.


Snitz 3.4 Readme | Like the support? Support Snitz too

Edited by - ruirib on 26 November 2004 19:11:52
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  19:16:29  Show Profile  Visit dayve's Homepage
nice class name

yeah, seems simple enough... I'll give it a whirl. It amazes me how uncomfortable I am at
times in a new area of programming, even though it is so similar to other things I have done.


Edited by - dayve on 26 November 2004 19:16:44
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  19:41:06  Show Profile  Visit dayve's Homepage
okay, since you're on a roll...

I've been able to upload the image.
I've been able to resmaple the images
I've been able to convert the image to .jpg, .gif and .png
I've been able to save data to the database


 void SendToDB(String FilePath, String UploadedFileName)
{
    OleDbConnection conImages;
    OleDbCommand cmdImgIns;
    string myConnString;
    string strSQL;
    
    myConnString = "Provider=SQLOLEDB;Data Source=SERVER; Initial Catalog=burningsoulsforum;User Id=******;Password=******; Connect Timeout=15;Network Library=dbmssocn;";
    conImages = new OleDbConnection( myConnString );
    
    strSQL = "INSERT INTO FORUM_IMAGES (I_LOC, I_MID) VALUES ('" + UploadedFileName + "', 2)";
    cmdImgIns = new OleDbCommand( strSQL, conImages );
    
    conImages.Open(); 
    cmdImgIns.ExecuteNonQuery();
    conImages.Close();
}


So, my final question is, how would you take the value of ImageName and insert it into an HTML textarea?
You can probably guess where I am going with this. Is there a way to write the variable name into HTML?
I saw something like <%@ ImageName%> but could not get it to work correctly. I was also thinking of using
an asp label.



Edited by - dayve on 26 November 2004 20:15:11
Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  20:02:33  Show Profile  Send ruirib a Yahoo! Message
I'm not sure what you mean, exactly. You want to read the info from the DB and show it a text area?


Snitz 3.4 Readme | Like the support? Support Snitz too
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  20:12:33  Show Profile  Visit dayve's Homepage
quote:
Originally posted by ruirib

I'm not sure what you mean, exactly. You want to read the info from the DB and show it a text area?


Just so you have an understanding of what my goals are here (I should have explained it earlier)

I am working on a script that my forum members can use to upload images. I am presently using a
Pure ASP version, but Windows 2003 has a limitation on Pure ASP uploads and I don't want to adjust
my MetaBase file to allow larger files. I found a .NET script using C# which allows you to upload
an image and it will resample it to a thumbnail. I am inserting the values for something to use later
but I want to take this newly uploaded image that was converted to a thumbnail and automatically pop
it into the text area... kind of like the original upload script a lot of Snitz Forums are using.
So, what I need to do is to figure out the best approach to reading the C# environment variables
into a javascript function. Using the Pure ASP version I can do something like this:

window.opener.document.PostTopic.Message.value+= '[img]uploaded/' + '<%=strFolder%>' + '/' + fname + '[/img]'


I am trying to figure out how to get the variables I've been using in the C# environment to accomplish
this.

Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  20:53:14  Show Profile  Send ruirib a Yahoo! Message
Ahhh... that complicates things a bit. I'm not (yet) that much experienced with ASP.NET. Getting a value into a control is easy, through Page_Load(), but I have never generated Javascript from C#. I can try and figure that out... tomorrow. It's getting late here.


Snitz 3.4 Readme | Like the support? Support Snitz too
Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 26 November 2004 :  21:06:48  Show Profile  Send ruirib a Yahoo! Message
Found a quick example. To generate a client side script within your code, a strategy could be this:

	private void Page_Load(object sender, System.EventArgs e)
   	{

		 String myString="Testing";
                 String myScript;

  		 myScript = "<script>" + "alert( '"+ myString + "');" + "</script>";
		 Page.RegisterStartupScript("ClientScript", myScript);
	}

		


Snitz 3.4 Readme | Like the support? Support Snitz too
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  23:01:44  Show Profile  Visit dayve's Homepage
thanks a lot for helping me through this... I am going to try the snippet now. I wouldn't have gotten through
this while keeping my sanity had it not been for your guidance. it is greatly appreciated.

Go to Top of Page
Page: of 3 Previous Topic Topic Next Topic  
Next Page
 New Topic  Topic Locked
 Printer Friendly
Jump To:
Snitz Forums 2000 © 2000-2021 Snitz™ Communications Go To Top Of Page
This page was generated in 0.22 seconds. Powered By: Snitz Forums 2000 Version 3.4.07