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
Previous Page | Next Page
Author Previous Topic Topic Next Topic
Page: of 3

dayve
Forum Moderator

USA
5820 Posts

Posted - 26 November 2004 :  23:20:40  Show Profile  Visit dayve's Homepage
I received a weird error when I tried it that stated CS1010: Newline in Constant. After
a quick search it said to break up the </script> tag because nesting <script> tags causes problems
so now it looks like this

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


and it works! Now to do my opener insert method.

Source: http://support.microsoft.com/?kbid=827420



Edited by - dayve on 26 November 2004 23:22:20
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 27 November 2004 :  02:50:49  Show Profile  Visit dayve's Homepage
Okay, everything is going great. One last hurdle. Having a difficult time getting the identity of the newly
inserted record.


<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Data" %>
<%@ 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 MemberID = Request.QueryString["mID"];
	   String FilePath = Request.PhysicalApplicationPath + "\\files\\~aspx\\";	
	   
	   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", "", RegexOptions.IgnoreCase);
		ImageName = Regex.Replace(ImageName, ".gif", "", RegexOptions.IgnoreCase);
		ImageName = Regex.Replace(ImageName, ".jpeg", "", RegexOptions.IgnoreCase);
		ImageName = Regex.Replace(ImageName, ".png", "", RegexOptions.IgnoreCase);

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

  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;
  }
 
 void SendToDB(String MemberID, 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, I_DATE) VALUES ('" + UploadedFileName + "', " + MemberID + ", '" + DateTime.Now + "') select IdentityInsert=@@identity";
    cmdImgIns = new OleDbCommand( strSQL, conImages );
    
    conImages.Open(); 
    cmdImgIns.ExecuteScalar();
    conImages.Close();
	
    String myScript;
	myScript = "<script>window.opener.document.PostTopic.Message.value+= '[img]files/~aspx/thumb_" + UploadedFileName + "[/img]';<"+"/script>";
	Page.RegisterStartupScript("ClientScript", myScript);
}  


</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>
PLEASE DO NOT USE - I AM TESTING!!!! <br />
<form id="MainForm" enctype="multipart/form-data" runat="server">
	<input id="PhotoUpload" runat="server" type="File">
	<asp:button ID="AddSaveButton" text="Upload" onclick="UploadBut_Click" cssclass="formcopy" runat="server" />
</form>
</body>
</html>


Edited by - dayve on 27 November 2004 02:52:40
Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 27 November 2004 :  03:46:28  Show Profile  Send ruirib a Yahoo! Message
Solving that is easy, you just need to run a query with this SQL statement: "SELECT @@IDENTITY As MyID"
This will return the value of the last identity field created.


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

dayve
Forum Moderator

USA
5820 Posts

Posted - 27 November 2004 :  11:24:13  Show Profile  Visit dayve's Homepage
If you look at my SQL statement you'd see I already did that, but every time I try
to pull the recordset value, it gives me an error. I think I am using the wrong
parameter in my execute statement.

I am using select IdentityInsert=@@identity which I got from SQLTeam. I also didn't
think I could append this to other sql statements, but I don't get an error if I don't
try to pull a recordset. The records get inserted just fine. It's only when I try
to pull the value that I get an error. From what I've been reading, I think I am using
the wrong parameter in my execute statement.

Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 27 November 2004 :  13:03:04  Show Profile  Send ruirib a Yahoo! Message
Dayve, don't do it like that. I have never did.

Here goes a suggestion:

strSQL = "INSERT INTO FORUM_IMAGES (I_LOC, I_MID, I_DATE) VALUES ('" + UploadedFileName + "', " + MemberID + ", '" + DateTime.Now + "')";
    cmdImgIns = new OleDbCommand( strSQL, conImages );
    
    conImages.Open(); 
    cmdImgIns.ExecuteNonQuery();

    cmdImgIns.CommandText="SELECT @@IDENTITY As MyID";
    OleDbDataReader reader=cmdImgIns.ExecuteReader();
    
    int id=reader.GetInt32(0);  //id will have the value you want
    reader.Close();
    conImages.Close();




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

dayve
Forum Moderator

USA
5820 Posts

Posted - 27 November 2004 :  20:18:07  Show Profile  Visit dayve's Homepage
Line 126:    cmdImgIns.CommandText="SELECT @@IDENTITY As MyID";
Line 127:    OleDbDataReader reader=cmdImgIns.ExecuteReader();    
Line 128:    int myid=reader.GetInt32(0);  //id will have the value you want
Line 129:    reader.Close();

Exception Details: System.InvalidOperationException: No data exists for the row/column.

Researching error now.

Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 27 November 2004 :  21:14:00  Show Profile  Visit dayve's Homepage
I noticed there was not a Read action initiated, so I added it but still get an error. Here is the function I am am using to write to the db.


 void SendToDB(String MemberID, 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, I_DATE) VALUES ('" + UploadedFileName + "', " + MemberID + ", '" + DateTime.Now + "')";
    cmdImgIns = new OleDbCommand( strSQL, conImages );    
    conImages.Open(); 
    cmdImgIns.ExecuteNonQuery();

    cmdImgIns.CommandText="SELECT @@IDENTITY As MyID";
    OleDbDataReader reader=cmdImgIns.ExecuteReader();   
    reader.Read(); 
    int MyID = reader.GetInt32(0); //id will have the value you want
    reader.Close();
	
    conImages.Close();	    
	
    String myScript;
	myScript = "<script>window.opener.document.PostTopic.Message.value+= '[img]files/~aspx/thumb_" + UploadedFileName + "[/img]';<"+"/script>";
	Page.RegisterStartupScript("ClientScript", myScript);
} 


The data value could not be converted for reasons other than sign mismatch or data overflow. For example, the data was corrupted in the data store but the row was still retrievable.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: The data value could not be converted for reasons other than sign mismatch or data overflow. For example, the data was corrupted in the data store but the row was still retrievable.

Source Error:


Line 127: OleDbDataReader reader=cmdImgIns.ExecuteReader();
Line 128: reader.Read();
Line 129: int MyId = reader.GetInt32(0); //id will have the value you want
Line 130: reader.Close();
Line 131:



Edited by - dayve on 28 November 2004 00:48:31
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 28 November 2004 :  00:46:50  Show Profile  Visit dayve's Homepage
Finally Got It!!! See red area below. This was the area that was kicking my butt. I needed a Read a Parse in order
to get it to work. Anyway, this has been fun. I think I'm all set now. Thanks for all your help.


    myConnString = "Provider=SQLOLEDB;Data Source=SERVER; Initial Catalog=burningsoulsforum;User Id=******;Password=******; Connect Timeout=15;Network Library=dbmssocn;";
  	strSQL = "INSERT INTO FORUM_IMAGES (I_LOC, I_MID, I_DATE) VALUES ('" + UploadedFileName + "', " + MemberID + ", '" + DateTime.Now + "');";    
	conImages = new OleDbConnection(myConnString);	
	cmdImgIns = new OleDbCommand(strSQL, conImages);    
    conImages.Open(); 
	cmdImgIns.ExecuteNonQuery();	
	cmdImgIns.CommandText="SELECT @@IDENTITY As 'Identity';";
    OleDbDataReader reader = cmdImgIns.ExecuteReader();
	reader.Read();
	int id = Int32.Parse(reader.GetValue(0).ToString());
    reader.Close();
    conImages.Close();	


Edited by - dayve on 28 November 2004 00:47:50
Go to Top of Page

ruirib
Snitz Forums Admin

Portugal
26364 Posts

Posted - 28 November 2004 :  04:45:40  Show Profile  Send ruirib a Yahoo! Message
You're right, I missed the read action. Sorry.

Anyway, I'm glad you got it working :):


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

snaayk
Senior Member

USA
1061 Posts

Posted - 03 December 2004 :  21:34:27  Show Profile  Visit snaayk's Homepage  Send snaayk an AOL message  Send snaayk an ICQ Message  Send snaayk a Yahoo! Message
I know it's a bit late, but to go lower case you can use:
.ToString().ToLower;
or if it's already a string .ToLower;

I haven't been around sharpening my c sharp :D

Did you get the rest figured out?
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 03 December 2004 :  23:12:00  Show Profile  Visit dayve's Homepage
quote:
Originally posted by snaayk

I know it's a bit late, but to go lower case you can use:
.ToString().ToLower;
or if it's already a string .ToLower;

I haven't been around sharpening my c sharp :D

Did you get the rest figured out?



oddly enough that was already in the script:

String fileName = PhotoUpload.PostedFile.FileName.ToLower();

the rest has been done for awhile now. I've been actively using this script along with some other modifications on my site now. It has been working absolutely perfectly.

Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 13 December 2004 :  00:58:23  Show Profile  Visit dayve's Homepage
Just discovered today that the following line ...

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

... seems to ignore the leading period. Someone uploaded an image with the word gift in it, no period, and gif was replaced.


Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 13 December 2004 :  01:44:34  Show Profile  Visit dayve's Homepage
found my answer...

ImageName = Regex.Replace(ImageName, @"\.gif", "", RegexOptions.IgnoreCase);

I knew I needed an escape character, but just using the slash would not work. I needed to prefix the search criteria with an ampersand.

Go to Top of Page

snaayk
Senior Member

USA
1061 Posts

Posted - 19 December 2004 :  02:13:12  Show Profile  Visit snaayk's Homepage  Send snaayk an AOL message  Send snaayk an ICQ Message  Send snaayk a Yahoo! Message
hmm...although you solved the problem, I think the solution would be:

ImageName = ImageName.ToLower().Replace(".gif", "");

This seems to have worked on a few different tests that I ran. I'm not sure if using Regex is more or less efficient - I've never used it myself - but it seems like overkill.

Also, why not delete anything after the (last) period? Unless you wanted to only delete certail file types, you could use:

ImageName = ImageName.Substring(0, int.Parse(ImageName.LastIndexOf(".").ToString().Replace("-1", ImageName.Length.ToString())));

Basically, find the last period, delete anything after it - if there is no period in the string, return the entire string.
Go to Top of Page

dayve
Forum Moderator

USA
5820 Posts

Posted - 19 December 2004 :  12:12:40  Show Profile  Visit dayve's Homepage
I don't believe C# has a built in Replace function which is why I had to use Regular Expressions Replace.

You said you tested this? I'll give it a whirl (the first example, not the second, I like visual simplification over efficiency at times)

Go to Top of Page
Page: of 3 Previous Topic Topic Next Topic  
Previous Page | 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.43 seconds. Powered By: Snitz Forums 2000 Version 3.4.07