save image on file system instead of DB - spring-mvc

I m developping an application where user can provide text informations and images. I want to save images on file system and in DB, I will add a link of each user to its images So I need to add the user ID to the image name to not get images with same name. I m using SPRING MVC.
in my Controller :
#RequestMapping(value="/save",method=RequestMethod.POST)
public String add ( #RequestParam("prix") Long prix,
RequestParam("adresse") String ville,
#RequestParam("categorie") String categorie,
#RequestParam("photos") MultipartFile file,
) throws FileNotFoundException
{
String chemin=null;
if (!file.isEmpty())
{
try {
String orgName = file.getOriginalFilename();
// this line to retreive just file name
String
name=orgName.substring(orgName.lastIndexOf("\\")+1,orgName.length());
chemin="e:\\images\\"+name; //here I want to add id (auto generated)
File file1=new File(chemin);
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
annonce.setImage(chemin);
annonce.setTitre(prix);
annonce.setCorps(ville);
annonce.setPrix(cetegorie)
annoncedao.save(annonce);
return "SuccessAddAnnonce";
}
but I can not get the ID witch is auto generated so I can not get it throw #RequestParam like adress or categorie because it is auto generated and I still don t have it until we call save method witch is last .
Any suggestions are welcome .

I got the Id using query with Select max (id)
#Query("SELECT MAX(id) FROM Annonce")
Long findAutoincrementAnnonce();
I wish help someone.

You can generate a random ID for each user and assign it to a particular user, and thus its image name also (what you intend to do here I guess).
I will illustrate it simply.
// Get a random ID coressponding to the user address or whatever, here i will just use address
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(ville.getBytes("UTF-8"));
String randomId = DatatypeConverter.printHexBinary(hash);
// Here you have a uniqueID for an address.
// You could have just used ville.hashCode() also but it might give you collisions with some different Strings.
if Input: "64th Street, Downtown, StackOverFlow" then
randomId = 8AB126F8EBC0F7B5CCBBEB3E21582ADF

Related

Exchange Web Services find item by unique id

I just started using Microsoft Exchange Web Services for the first time. Want I want to be able to do is the following:
Create Meeting
Update Meeting
Cancel/Delete Meeting
These meetings are created in an ASP.NET MVC application and saved into a SQL Server database. I simply wish to integrate this with the on site Exchange Server. So far, I'm able to created my meeting with the following code:
public static Task<string> CreateMeetingAsync(string from, List<string> to, string subject, string body, string location, DateTime begin, DateTime end)
{
var tcs = new TaskCompletionSource<string>();
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = CredentialCache.DefaultNetworkCredentials;
//service.UseDefaultCredentials = true;
// I suspect the Service URL needs to be set from the user email address because this is then used to set the organiser
// of the appointment constructed below. The Organizer is a read-only field that cannot be manually set. (security measure)
service.AutodiscoverUrl(from);
//service.Url = new Uri(WebConfigurationManager.AppSettings["ExchangeServer"]);
Appointment meeting = new Appointment(service);
meeting.Subject = subject;
meeting.Body = "<span style=\"font-family:'Century Gothic'\" >" + body + "</span><br/><br/><br/>";
meeting.Body.BodyType = BodyType.HTML;
meeting.Start = begin;
meeting.End = end;
meeting.Location = location;
meeting.ReminderMinutesBeforeStart = 60;
foreach (string attendee in to)
{
meeting.RequiredAttendees.Add(attendee);
}
meeting.Save(SendInvitationsMode.SendToAllAndSaveCopy);
tcs.TrySetResult(meeting.Id.UniqueId);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}
This successfully creates my meeting, places it into the user's calendar in outlook and sends a meeting request to all attendees. I noticed the following exception when attempting to call meeting.Save(SendInvitationsMode.SendToAllAndSaveCopy); twice:
This operation can't be performed because this service object already has an ID. To update this service object, use the Update() method instead.
I thought: Great, it saves the item in exchange with a unique id. I'll save this ID in my application's database and use it later to edit/cancel the meeting. That is why I return the id: tcs.TrySetResult(meeting.Id.UniqueId);
This is saved nicely into my application's database:
Now, I am attempting to do the next part where I update the meeting, but I cannot find a way to search for the item based on the unique identifier that I'm saving. An example I found on code.msdn uses the service.FindItems() method with a query that searches the subject:
string querystring = "Subject:Lunch";
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Calendar, querystring, view);
I don't like this. There could be a chance that the user created a meeting outside of my application that coincidentally has the same subject, and here come's my application and cancel's it. I tried to determine wether it's possible to use the unique id in the query string, but this does not seem possible.
I did notice on the above query string page that the last property you can search on is (property is not specified) that searches in "all word phase properties.". I tried thus simply putting the id into the query, but this returns no results:
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Calendar, "AAMkADJhZDQzZWFmLWYxYTktNGI1Yi1iZTA5LWVmOTE3MmJiMGIxZgBGAAAAAAAqhOzrXRdvRoA6yPu9S/XnBwDXvBDBMebkTqUWix3HxZrnAAAA2LKLAAB5iS34oLxkSJIUht/+h9J1AAFlEVLAAAA=", view);
Use the Appointment.Bind static function, providing a service object and the ItemId saved in your database. Be aware with meeting workflow (invite, accept, reject) can re-create a meeting on the same calendar with a new ItemId. But if you are just looking at the meeting you make on your own calendar, you should be OK.

Why are my users not able to verify their email address?

I'm using a uniqueidentifier to validate the email address of a user in my ASP.NET application. When I try to validate any email address using the uniqueidentifier, I can do so without problem. 80% of my users, however, cannot do so. I cannot figure out why this is happening! I've had users email me directly, forwarding their activation email and I can activate their account without issue.
Here's an example of the validation link that's in the email.
mysite.org/petition.aspx?uid=0fcc9582-386c-4738-943d-36e09c8df4bd
Here's the exception that's occurring:
problem loading petition screen: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).:
at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithDashes(String guidString, GuidResult& result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
at System.Guid..ctor(String g)
at MAP.Umbraco.UserControls.SignPetitionUserControl.get_PetitionGuid()
at MAP.Umbraco.UserControls.SignPetitionUserControl.OnLoad(EventArgs e)
UPDATE: Here's the get method for my PetitionGuid property.
private Guid? PetitionGuid
{
get
{
if (Page.Request.QueryString["uid"] == null)
return null;
else
return new Guid( Page.Request.QueryString["uid"].ToString());
}
}
Is there anything obvious that I'm missing here?
Feel free to ask any questions that you might need to ask.
You're missing a character.
0fcc9582-386c-4738-943d-36e09c8df4b <---
12345678 1234 1234 1234 123456789012
Update
Based on your update above, your implementation for petition guid is not coded very defensively.
private Guid? PetitionGuid
{
get
{
if (Page.Request.QueryString["uid"] == null)
return null;
else
return new Guid( Page.Request.QueryString["uid"].ToString());
}
}
so basically, if the uid parameter is ANYTHING other than null, (a number, random string, other garbage) you are going to try and turn it into a guid. and that's obviously causing failures... put some logging in, and record the values of UID that are being submitted.
You should probably be using something like tryParse, instead of just puking an exception.
if(string.IsNullOrEmpty(s))
Console.WriteLine("Null or Empty");
Guid g;
Guid.TryParse(s, out g);
if(g == Guid.MinValue)
Console.WriteLine("Couldn't Parse");
else
Console.WriteLine("G: {0}", g);
Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
Does tihs 0fcc9582-386c-4738-943d-36e09c8df4b meet to requirement? You lost one digit in last part. You have 11 digit instead of 12.
Based on the current answers and comments and the fact that you use Umbraco I supect the QueryString is delivered to you in an encoded form. Better make sure that what we get is sane and valid and in the format we can actually handle it. The main improvement is in usimg HttpUtility.Decode to get the querystring into shape.
private Guid? PetitionGuid
{
get
{
Guid? guid = null;
var raw = Page.Request.QueryString["uid"];
if (!String.IsNullOrEmpty(raw))
{
var decoded = HttpUtility.UrlDecode(raw);
Guid parsed;
if (Guid.TryParse(decoded, out parsed))
{
guid = parsed;
}
else
{
Trace.WriteLine(String.Format(
"illigal uid {0}:{1}", raw,decoded));
}
}
return guid;
}
}

Add new tags on dcm4chee

I'm working with dcm4chee now,and I have the demand to add some custom fields,for example patient's ID card number,mobile fhone number and address.
After googling some related information,I am still confused and don't know what to do.Has any one ever done this?
i've done it on some other cases. In my case i've to modify existing tag with new value. Here the code, hope it give you some pointer.
public static void changementTag(File file, int tagChooser, String aModify, VR vr, String newString )
{
try
{
DicomInputStream dis = new DicomInputStream(file);
DicomObject dio = dis.readDicomObject();
dis.close();
String fileName = file.getAbsolutePath() + ".ori";
File originFile = new File(fileName);
file.renameTo(originFile);
boolean change = false;
dio.putString(tagChooser, vr, newString);
change = true;
if(change)
{
FileOutputStream fos = new FileOutputStream( new File(file.getParent()+ "/" + file.getName()));
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dos = new DicomOutputStream(bos);
dos.writeDicomFile(dio);
dos.close();
originFile.delete();
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
As already pointed out by #jap1968, you can add
Other Patient IDs (0010,1000)
to include any additional patient ID numbers. This attribute is part of the Patient Identification Module, which attributes are generally expected in most DICOM objects.
From the Patient Demographic Module, which is normally an optional set of attributes, you can then for example reuse these attributes:
Patient’s Telephone Numbers (0010,2154)
Patient’s Address (0010,1040)
Depending on which DICOM toolkit you are using to process your DICOM objects, there will be different methods for attribute insertion. In dcm4che, you should be able to use one of the available DicomObject.put... methods to insert a new value in your DICOM object. Just remember that for correctness, you should update the SOP Instance UID (and potentially other UID:s) for the modified object.
Have a look at these Dicom fields:
Other Patient IDs (0010,1000)
Other Patient IDs Sequence (0010,1002)
Maybe you do not need to add custom fields (at least for the patient ID card), but just use some of the already existing ones.

Making SlideShowExtender retrieve images from MS Access database

In my Microsoft access database I have a table called Picture and 3 fields: ID, Name, Image. I was wondering if it was possible to get all the images from the field 'Image' and display them into SlideShowExtender.
Are there any examples or explanations to do this?
I think you should use other slide show tools like "http://www.twospy.com/galleriffic/" It is so simple to use
If your images are stored in the Access database, then you will first have to create a handler to display them. This handler will get the bytes our of the Image column based on the ID and send the bytes back to the browser as an image. See this for an example:
Using ASHX files to retrieve DB images
With that in place you can display an image like this:
<asp:Image runat="server" ImageUrl="~/DatabaseImagehandler.ashx?id=42" />
The SlideShowExtender expects a service to provide it with an array of slides, so this service should basically return this:
// Based on SELECT COUNT(Id) FROM Images
int count = 5;
// Create the array of slides
AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[count];
// Put the URL and name for each image in the array
// Reader based on SELECT Id, Name FROM Images
int index = 0;
while(reader.Read()) {
string id = reader["Id"].ToString();
string name = reader["Name"].ToString();
string.path = Server.MapPath("~/DatabaseImagehandler.ashx?id=" + id);
// Create slide object with path set to point to the handler
AjaxControlToolkit.Slide slide = new AjaxControlToolkit.Slide(path, name, "img" + id);
slides[index] = slide;
index++;
}
return slides;

ASP.NET 4 : Comparing the result set of an object and a string

I am retrieving the contents of a database using a object (its returning only one field) and then comparing it with a string which has been hashed with SHA1 .The code is as follows :
protected void Onbutton_click_login(object sender, System.EventArgs e)
{
var dbcontext = new PrepLicensingSolution2010.DAL.LicensingEntities1();
var user = dbcontext.getloginname(loginName.Text);
string HashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text, "sha1");
if (user.ToString() == HashedPassword)
{
Response.Redirect("faqs.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
I put breakpoints and checked the data at each stage of the flow and the data in the object result set and in the string are the same but even then the conditional if fails
whats interesting is both the types being compared are of the type string and of the same value,so why is that that the redirect goes to the default.aspx page.
The image contains the data from the breakpoints
Any inputs would be great.
Thanks
Based on the screenshot, user.ToString() looks to be returning the string {System.Data.Objects.ObjectResult<string>}. This, of course, does not equal the hashed password.
Your problem is that the result of your getloginname call is a sequence of strings containing a single string, not a single string itself. The default implementation of ToString() simply returns the class name, and you can see it in the Value column for the "user" row in the screenshot. Changing your conditional statement to the following should fix it:
if (user.FirstOrDefault() == HashedPassword)

Resources