How to insert current date and time when user insert data in database - asp.net-mvc-4

I am trying to insert data into database. i am basically trying to get current date , I am also hiding that particular field("Update Date) because I do want the user to see. Now all I am wanting is whenever i insert some data to database created date should automatically inserted.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreImageCreateVM StoreImageVM)
{
if (ModelState.IsValid)
{
try
{
StoreImageLogic.Insert(StoreImageVM);
}
catch (Exception e)
{
TempData["Failure"] = "Creation Failed. Image too large.";
return View(StoreImageVM);
}
TempData["Success"] = "Creation Successful";
return RedirectToAction("Index", new { id = StoreImageVM.StoreID });
}
return View(StoreImageVM);
}
savechangesmethod
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = imageVM.uploadDate;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}

i just add to change the savechangesmethod by using the DateTime.Now method. see below.
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = DateTime.Now;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
}

Related

Pdf file renaming and deleting not working in Android 10 using MediaStore

I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....

FileStore.CreateFile returns ntStatus = 3221226071

I am using this SMBLibrary. Related to this closed issue, I sometimes get ntStatus = 3221226071 when I attempt to FileStore.CreateFile(). What does "DFS pathname not on local server" mean? If I keep trying, eventually it will work. Leads me to believe some resources are being held or not released/disconnected. Any ideas here?
"SMBLibrary" Version="1.4.8"
Here is my code:
[Fact]
public void Unit_Test_To_Test_SMBLibrary()
{
var server = "myRemoteServer";
var shareName = "shareddir";
var windowsPath = "Data\\Folder1\\unittest";
var random = new System.Random();
var filename = "createdBySmbclient" + random.Next(1, 10).ToString() + ".txt";
var domain = "my.domain";
var username = "myUser";
var password = "--put secret password here--";
var client = new SMB2Client();
bool isConnected = client.Connect(server, SMBTransportType.DirectTCPTransport);
if(isConnected)
{
try
{
NTStatus ntStatus = client.Login(domain, username, password);
if (ntStatus == NTStatus.STATUS_SUCCESS)
{
ISMBFileStore fileStore = client.TreeConnect(shareName, out ntStatus);
object fileHandle;
FileStatus fileStatus;
var windowsPathWithFile = Path.Combine(windowsPath, filename);
// 1st, create empty file.
ntStatus = fileStore.CreateFile(
out fileHandle,
out fileStatus,
windowsPathWithFile,
AccessMask.GENERIC_READ | AccessMask.GENERIC_WRITE,
0,
ShareAccess.None,
CreateDisposition.FILE_OPEN_IF,
CreateOptions.FILE_NON_DIRECTORY_FILE,
null
);
// create file contents and get the bytes
byte[] filebytes = Encoding.ASCII.GetBytes("hello world");
// 2nd, write data to the newly created file
if (ntStatus == NTStatus.STATUS_SUCCESS && fileStatus == FileStatus.FILE_CREATED)
{
int numberOfBytesWritten;
ntStatus = fileStore.WriteFile(out numberOfBytesWritten, fileHandle, 0, filebytes);
fileStore.FlushFileBuffers(fileHandle);
fileStore.CloseFile(fileHandle);
fileStore.Disconnect();
_logger.LogDebug(string.Format("Export successful: {0}", windowsPathWithFile));
}
else
{
throw new Exception(string.Format("ERROR: ntStatus = {0}, fileStatus = {1}", ntStatus, fileStatus));
}
}
}
finally
{
client.Logoff();
client.Disconnect();
}
}
}

REST based Multiple file Upload With additional Properties(Parameters) C# WCF

I have a WCF service which used multipart/Form-Data, How can i get the properties and the files uploaded
Finally i got my service working.
I have created a multiparser.
public class MultipartParser
{
public MultipartParser(Stream stream)
{
this.Parse(stream, Encoding.UTF8);
}
public static byte[][] Separate(byte[] source, byte[] separator)
{
var Parts = new List<byte[]>();
var Index = 0;
byte[] Part;
for (var I = 0; I < source.Length; ++I)
{
if (Equals(source, separator, I))
{
Part = new byte[I - Index];
Array.Copy(source, Index, Part, 0, Part.Length);
Parts.Add(Part);
Index = I + separator.Length;
I += separator.Length - 1;
}
}
Part = new byte[source.Length - Index];
Array.Copy(source, Index, Part, 0, Part.Length);
Parts.Add(Part);
return Parts.ToArray();
}
public static bool Equals(byte[] source, byte[] separator, int index)
{
for (int i = 0; i < separator.Length; ++i)
if (index + i >= source.Length || source[index + i] != separator[i])
return false;
return true;
}
private void Parse(Stream stream, Encoding encoding)
{
Regex regQuery;
Match regMatch;
string propertyType;
// The first line should contain the delimiter
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1)
{
string delimiterString = content.Substring(0, content.IndexOf("\r\n"));
byte[] delimiterBytes = encoding.GetBytes(delimiterString);
byte[] delimiterWithNewLineBytes = encoding.GetBytes(delimiterString + "\r\n");
// the request ends DELIMITER--\r\n
byte[] delimiterEndBytes = encoding.GetBytes("\r\n" + delimiterString + "--\r\n");
int lengthDifferenceWithEndBytes = (delimiterString + "--\r\n").Length;
byte[][] separatedStream = Separate(data, delimiterWithNewLineBytes);
data = null;
for (int i = 0; i < separatedStream.Length; i++)
{
// parse out whether this is a parameter or a file
// get the first line of the byte[] as a string
string thisPieceAsString = encoding.GetString(separatedStream[i]);
if (string.IsNullOrWhiteSpace(thisPieceAsString)) { continue; }
string firstLine = thisPieceAsString.Substring(0, thisPieceAsString.IndexOf("\r\n"));
// Check the item to see what it is
regQuery = new Regex(#"(?<=name\=\"")(.*?)(?=\"")");
regMatch = regQuery.Match(firstLine);
propertyType = regMatch.Value.Trim();
// get the index of the start of the content and the end of the content
int indexOfStartOfContent = thisPieceAsString.IndexOf("\r\n\r\n") + "\r\n\r\n".Length;
// this line compares the name to the name of the html input control,
// this can be smarter by instead looking for the filename property
StreamContent myContent = new StreamContent();
if (propertyType.ToUpper().Trim() != "FILES")
{
// this is a parameter!
// if this is the last piece, chop off the final delimiter
int lengthToRemove = (i == separatedStream.Length - 1) ? lengthDifferenceWithEndBytes : 0;
string value = thisPieceAsString.Substring(indexOfStartOfContent, thisPieceAsString.Length - "\r\n".Length - indexOfStartOfContent - lengthToRemove);
myContent.StringData = value;
myContent.PropertyName = propertyType;
if (StreamContents == null)
StreamContents = new List<StreamContent>();
StreamContents.Add(myContent);
this.Success = true;
}
else
{
// this is a file!
regQuery = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
regMatch = regQuery.Match(firstLine);
string fileName = regMatch.Value.Trim();
// get the content byte[]
// if this is the last piece, chop off the final delimiter
int lengthToRemove = (i == separatedStream.Length - 1) ? delimiterEndBytes.Length : 0;
int contentByteArrayStartIndex = encoding.GetBytes(thisPieceAsString.Substring(0, indexOfStartOfContent)).Length;
byte[] fileData = new byte[separatedStream[i].Length - contentByteArrayStartIndex - lengthToRemove];
Array.Copy(separatedStream[i], contentByteArrayStartIndex, fileData, 0, separatedStream[i].Length - contentByteArrayStartIndex - lengthToRemove);
// save the fileData byte[] as the file
myContent.PropertyName = propertyType;
myContent.FileName = fileName;
myContent.IsFile = true;
myContent.Data = fileData;
if (StreamContents == null)
StreamContents = new List<StreamContent>();
StreamContents.Add(myContent);
this.Success = true;
}
}
}
}
private byte[] ToByteArray(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public List<StreamContent> StreamContents { get; set; }
public bool Success
{
get;
private set;
}
public string ContentType
{
get;
private set;
}
public string Filename
{
get;
private set;
}
public List<byte[]> FileContents
{
get;
private set;
}
}
public class StreamContent
{
public byte[] Data { get; set; }
public bool IsFile { get; set; }
public string FileType { get; set; }
public string FileName { get; set; }
public string PropertyName { get; set; }
public string StringData { get; set; }
}`
Using this parser u could get the properties and their values in the List object. In the service Use the following
MultipartParser parser = new MultipartParser(stream);
if (parser != null && parser.Success)
{
foreach (var content in parser.StreamContents)
{
if (content.IsFile) // if file
{
string path = "Your Path";
//content.FileName; file Name
//content.Data File contents in byte[]
// Write the file to the path specifies
File.WriteAllBytes(path+content.FileName, content.Data);
continue;
}
//content.PropertyName; gives u the Parameter
//content.StringData; gives u the value of the parameter
}
}

pass string variable from view to controller in mvc4

my view is:
<script type="text/javascript">
$('#Body').redactor({
fileUpload: "#Url.Action(controllerName: "RedactorUpload", actionName: "FileUpload")"
, autoformat: false
, convertDivs: false
, direction: 'rtl'
, autoresize: false
});
my action in controller is:
[HttpPost]
[AllowUploadSafeFiles]
public virtual ActionResult FileUpload(HttpPostedFileBase file,string section)
{
ActionResult result;
string fileName = Path.GetFileName(file.FileName);
string relativePath = "/Content/"+section+"/Files/";
string absolutePath = Server.MapPath("~" + relativePath + fileName);
if (file.ContentLength > 0 && fileName != null)
{
file.SaveAs(absolutePath);
var array = new { filelink = relativePath + fileName, filename = fileName };
result = Json(array, System.Net.Mime.MediaTypeNames.Text.Plain, JsonRequestBehavior.AllowGet);
}
else
{
result = Content("invalid file!");
}
return result;
}
I want to send section from my view to action. section is string variable. relativePath variable in action is dynamic and is determined from view (by parameter is passed from view).

Rewriting from MonoTouch Application to MonoDroid

I'm going to rewrite the application from Monotouh to Monodroid application for android. Correct me if I'm wrong. The logic remains the same as in MonoTouch or change anything? If something changes, please tell me, what?
As far as I understand, only GIU changes. Thanks in advance!
So, this is my code where i call data from my server:
namespace Mobile{
public static class SiteHelper
{
public static string DbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Sql_1.4.sqlite");
public const string TempDbPath = "./Sql.sqlite";
public static UIView View { get; set; }
public static BaseController Controller { get; set; }
private static event NIHandler _noInternetHandler;
private static bool _noInternetShoved = false;
public static string SiteDomain = "http://mysite.com"; //files which connecting to the DB on server (.asx files)
private delegate void NIHandler ();
public static XDocument DoRequest (string Request)
{
if (_noInternetHandler != null) {
foreach (var del in _noInternetHandler.GetInvocationList()) {
_noInternetHandler -= del as NIHandler;
}
}
if (Controller != null)
_noInternetHandler += new NIHandler (Controller.PushThenNoInternet);
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"myprogMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
UIActivityIndicatorView _preloader = null;
if (Controller != null) {
Controller.InvokeOnMainThread (delegate() {
_preloader = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
if (View != null && Request.IndexOf ("login.ashx") == -1
&& Request.IndexOf ("yandex") == -1
&& Request.IndexOf ("GetDialogMessages") == -1) {
lock (_preloader) {
if (_preloader != null && !_preloader.IsAnimating)
_preloader.HidesWhenStopped = true;
_preloader.Frame = new RectangleF (150, 170, 30, 30);
_preloader.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale ((float)1.3, (float)1.3);
_preloader.StartAnimating ();
View.Add (_preloader);
}
}
});
}
/*ctx.GetText(Resource.String.SiteAddress)*/
Stream Stream = null;
try {
HttpWebRequest request = new HttpWebRequest (new Uri (SiteDomain + "/FolderWithFiles/" + CryptoString));
request.Timeout = 8000;
Stream = request.GetResponse ().GetResponseStream ();
_noInternetShoved = false;
if (_noInternetHandler != null)
_noInternetHandler -= new NIHandler (Controller.PushThenNoInternet);
} catch (WebException) {
if (_noInternetHandler != null)
_noInternetHandler.Invoke ();
var resp = new XDocument (new XElement ("Response",
new XElement ("status", "error"),
new XElement ("error", "Отсутствует интернет"))
);
return resp;
}
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp.Substring (0, Resp.IndexOf ("<html>") == -1 ? Resp.Length : Resp.IndexOf ("<!DOCTYPE html>")));
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (Controller != null && _preloader != null) {
Controller.InvokeOnMainThread (delegate() {
lock (_preloader) {
_preloader.StopAnimating ();
_preloader.RemoveFromSuperview ();
}
});
}
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static XDocument DoWriteFileRequest (string Request, byte[] file)
{
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"mobileMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create (SiteDomain + "/misc/mobile/" + CryptoString);
Req.Method = "POST";
Stream requestStream = Req.GetRequestStream ();
requestStream.Write (file, 0, file.Length);
requestStream.Close ();
Stream Stream = Req.GetResponse ().GetResponseStream ();
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp);
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static string GetMd5Hash (MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder ();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append (data [i].ToString ("x2"));
}
// Return the hexadecimal string.2
return sBuilder.ToString ();
}
//Geting the info for my app
public static List<PackageListModel> GetUserPackages (int UserID)
{
List<PackageListModel> Events = new List<PackageListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
PackageListModel Event = null;
Event = new PackageListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Title = el.Element("Title").Value,
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
ImageUrl = el.Element("ImageUrl").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
//Получить пользовательские поездки
public static List<TransporterListModel> GetUserTransporters (int UserID)
{
List<TransporterListModel> Events = new List<TransporterListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
TransporterListModel Event = null;
Event = new TransporterListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
TransportsStr = el.Element("Transports").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
}
}
}
I think you should read this.
In brief - you can reuse application logic that not depends on platform-specific parts, so working with database/server can be shared between MonoTouch and Mono for Android.