Getting DidReceiveMemoryWarning all the time when working with images - c#

Attaching the source code for application i have created, its a simple application with collection view and button to choose image from gallery or camera. ios app crashes after taking 8 images continuously from camera.
using CoreGraphics;
using Foundation;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using UIKit;
namespace App2.iOS
{
public class imagesDisplay
{
public bool PlusImg;
public bool uploaded;
public string path { get; set; }
public int id { get; set; }
public imagesDisplay(bool uploaded, bool PlusImg = false, string path = null, int id = 0)
{
this.uploaded = uploaded;
this.PlusImg = PlusImg;
this.path = path;
this.id = id;
}
}
public partial class ViewController : UIViewController
{
public List<imagesDisplay> images = new List<imagesDisplay>();
private UIAlertController alert;
private UIImagePickerController imagePicker;
private NSData imgData;
private NSData thumdata;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
imgCollection.SetCollectionViewLayout(new LineLayout(), false);
imgCollection.AllowsMultipleSelection = true;
imgCollection.RegisterNibForCell(UINib.FromName("imageceCollectionViewCell", null), imageceCollectionViewCell.Key);
alert = UIAlertController.Create("", "Select image from : ", UIAlertControllerStyle.ActionSheet);
var cameraaction = UIAlertAction.Create("Bruk kamera", UIAlertActionStyle.Default, a =>
{
imagePicker = new UIImagePickerController();
imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
imagePicker.Canceled += Handle_Canceled;
imagePicker.AllowsImageEditing = false;
this.NavigationController.PresentViewController(imagePicker, true, null);
});
alert.AddAction(cameraaction);
var galleryaction = UIAlertAction.Create("Last opp bilder", UIAlertActionStyle.Default, a =>
{
imagePicker = new UIImagePickerController();
imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
imagePicker.Canceled += Handle_Canceled;
imagePicker.AllowsImageEditing = false;
this.NavigationController.PresentViewController(imagePicker, true, null);
});
alert.AddAction(galleryaction);
alert.AddAction(UIAlertAction.Create("Avbryt", UIAlertActionStyle.Cancel, a => { }));
imgCollection.Source = new ImageCollectionSource(images,new WeakReference<UINavigationController>(this.NavigationController));
}
public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
partial void UIButton125_TouchUpInside(UIButton sender)
{
this.PresentViewController(alert, true, null);
}
private void Handle_Canceled(object sender, EventArgs e)
{
imagePicker.DismissModalViewController(true);
}
private void Handle_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
{
try
{
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
if (referenceURL != null)
Console.WriteLine("Url:" + referenceURL.ToString());
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if (originalImage != null)
{
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff");
string jpgFilename = System.IO.Path.Combine(documentsDirectory, timestamp + ".jpg"); // hardcoded filename, overwritten each time
string thumname = System.IO.Path.Combine(documentsDirectory, timestamp + "_thumb" + ".jpg");
imgData = originalImage.AsJPEG();
Console.WriteLine("Original image size = " + imgData.Length);
thumdata = originalImage.AsJPEG(0.0f);
Console.WriteLine("after funtion compresion image size = " + thumdata.Length);
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
NSError err1 = null;
if (thumdata.Save(thumname, false, out err1))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
images.Add(new imagesDisplay(false, false, thumname, 0));
}
imgCollection.ReloadData();
imagePicker.DismissViewController(true, null);
}
catch (Exception ex)
{
}
}
}
public class LineLayout : UICollectionViewFlowLayout
{
public LineLayout()
{
ItemSize = new CGSize((UIScreen.MainScreen.Bounds.Width / 2) - 12, (UIScreen.MainScreen.Bounds.Height / 3) - 40);
MinimumInteritemSpacing = 0f;
}
}
}

Force to release the image data before creating the new one:
if (imgData != null) {
imgData.Dispose();
imgData = null;
}
imgData = originalImage.AsJPEG();
Or use local variable with using sentence:
using (NSData imgData = originalImage.AsJPEG()) { //imgData will be disposed immediately at the end of block
//......
}

Related

Find and Replace text in all Game Objects in a Unity Project

I have a couple of asks to update some text throughout a project. Doing a find and replace in code is easy, but I would like to implement a tool to look through all game objects. Unfortunately, I can grab all of the game objects in the scene, but I have not found a solution to grab all of the game objects in the project. Does anyone have any suggestions?
This is my current approach:
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using EditorPlayerSettings = UnityEditor.PlayerSettings;
namespace UnityEditor.XCodeEditor
{
public class FindAndReplaceToolbar : EditorWindow
{
private const string TAG = "FindAndReplace";
string mOldValue = string.Empty;
string mNewValue = string.Empty;
[MenuItem("Window/Find And Replace")]
void Init()
{
var window = GetWindow<FindAndReplaceToolbar>(false, "Find And Replace Toolbar");
window.minSize = new Vector2(10, 10);
window.Show();
}
void OnGUI()
{
GUILayout.BeginHorizontal();
{
mOldValue = EditorGUILayout.TextField("Find: ", mOldValue, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
mNewValue = EditorGUILayout.TextField("Replace: ", mNewValue, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Find and Replace"))
{
FindAndReplace();
}
GUILayout.EndHorizontal();
}
#region Find And Replace Helper
public void FindAndReplace()
{
Debug.Log($"{TAG} Started: ({mOldValue} - {mNewValue})");
foreach (var textMeshProUGUI in GetAllTextMeshProUGUIsInScene())
{
if (textMeshProUGUI.text.Contains(mOldValue))
{
Debug.Log($"{TAG} Replaced {mOldValue} in {textMeshProUGUI.name} with {mNewValue} (See {GetFileName(textMeshProUGUI.transform)})");
textMeshProUGUI.text = textMeshProUGUI.text.Replace(mOldValue, mNewValue);
}
}
Debug.Log($"{TAG} Finished: ({mOldValue} - {mNewValue})");
}
public List<TextMeshProUGUI> GetAllTextMeshProUGUIsInScene()
{
List<TextMeshProUGUI> objectsInScene = new List<TextMeshProUGUI>();
foreach (TextMeshProUGUI go in (TextMeshProUGUI[]) Resources.FindObjectsOfTypeAll(typeof(TextMeshProUGUI)))
{
if (!EditorUtility.IsPersistent(go.transform.root.gameObject) && !(go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave))
{
objectsInScene.Add(go);
}
}
return objectsInScene;
}
public static string GetFileName(Transform transform)
{
try
{
var parent = transform;
while (parent.parent != null)
{
parent = parent.parent;
}
return parent.name;
}
catch (Exception)
{
return transform.name;
}
}
#endregion Find And Replace Helper
}
}
#hijinxbassist pointed me in the right direction. Here is my current solution:
using System;
using System.IO;
using UnityEngine;
using EditorPlayerSettings = UnityEditor.PlayerSettings;
namespace UnityEditor.XCodeEditor
{
[InitializeOnLoad]
public class FindAndReplaceToolbar : EditorWindow
{
private const string TAG = "FindAndReplace";
private string mOldValue = string.Empty;
private string mNewValue = string.Empty;
static FindAndReplaceToolbar()
{
Debug.Log($"{TAG} InitializeOnLoad");
}
[MenuItem("Window/Find And Replace")]
static void Init()
{
var window = GetWindow<FindAndReplaceToolbar>(false, "Find And Replace Toolbar");
window.minSize = new Vector2(10, 10);
window.Show();
}
void OnGUI()
{
GUILayout.BeginHorizontal();
{
mOldValue = EditorGUILayout.TextField("Find: ", mOldValue, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
mNewValue = EditorGUILayout.TextField("Replace: ", mNewValue, GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Find and Replace"))
{
FindAndReplace();
}
GUILayout.EndHorizontal();
}
public void FindAndReplace()
{
Debug.Log($"{TAG}: Started: ({mOldValue} - {mNewValue})");
string[] assetGUIDs = AssetDatabase.FindAssets("t:Object");
for (int i = 0; i < assetGUIDs.Length; i++)
{
try
{
string guid = assetGUIDs[i];
string assetFilePath = AssetDatabase.GUIDToAssetPath(guid);
string assetFile = File.ReadAllText(assetFilePath);
if (assetFile.Contains(mOldValue))
{
assetFile = assetFile.Replace(mOldValue, mNewValue);
File.WriteAllText(assetFilePath, assetFile);
Debug.Log($"{TAG}: Replaced {mOldValue} with {mNewValue} in Asset: [{Path.GetFileName(assetFilePath)}] (Type: {AssetDatabase.GetMainAssetTypeAtPath(assetFilePath)})");
}
}
catch (Exception e)
{
Debug.Log($"{TAG}: {e.Message}");
}
}
Debug.Log($"{TAG}: Finished: ({mOldValue} - {mNewValue})");
}
}
}

How to find items in a ListBox?

I am creating an application where I have a ListBox which has items that are read in from a text file using StreamReader. I have created a search form but I'm not sure what to do next. Can anyone give me some suggestions please? Here is my code:
My code for the ListBox (sorry it's so long)
public partial class frmSwitches : Form
{
public static ArrayList switches = new ArrayList();
public static frmSwitches frmkeepSwitches = null;
public static string inputDataFile = "LeckySafe.txt";
const int numSwitchItems = 6;
public frmSwitches()
{
InitializeComponent();
frmkeepSwitches = this;
}
private void btnDevices_Click(object sender, EventArgs e)
{
frmDevices tempDevices = new frmDevices();
tempDevices.Show();
frmkeepSwitches.Hide();
}
private bool fileOpenForReadOK(string readFile, ref StreamReader dataIn)
{
try
{
dataIn = new StreamReader(readFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when reading data in) - File could not be found.\n"
+ notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when reading data in) - Operation failed.\n"
+ e.Message);
return false;
}
}
private bool getNextSwitch(StreamReader inNext, string[] nextSwitchData)
{
string nextLine;
int numDataItems = nextSwitchData.Count();
for (int i = 0; i < numDataItems; i++)
{
try
{
nextLine = inNext.ReadLine();
if (nextLine != null)
nextSwitchData[i] = nextLine;
else
{
return false;
}
}
catch (Exception e)
{
MessageBox.Show("ERROR Reading from file.\n" + e.Message);
return false;
}
}
return true;
}
private void readSwitches()
{
StreamReader inSwitches = null;
Switch tempSwitch;
bool anyMoreSwitches = false;
string[] switchData = new string[numSwitchItems];
if (fileOpenForReadOK(inputDataFile, ref inSwitches))
{
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
while (anyMoreSwitches == true)
{
tempSwitch = new Switch(switchData[0], switchData[1], switchData[2], switchData[3], switchData[4], switchData[5]);
switches.Add(tempSwitch);
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
}
}
if (inSwitches != null) inSwitches.Close();
}
public static bool fileOpenForWriteOK(string writeFile, ref StreamWriter dataOut)
{
try
{
dataOut = new StreamWriter(writeFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when writing data out)" +
"- File could not be found.\n" + notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when writing data out)" +
"- Operation failed.\n" + e.Message);
return false;
}
}
public static void writeSwitches()
{
StreamWriter outputSwitches = null;
if (fileOpenForWriteOK(inputDataFile, ref outputSwitches))
{
foreach (Switch currSwitch in switches)
{
outputSwitches.WriteLine(currSwitch.getSerialNo());
outputSwitches.WriteLine(currSwitch.getType());
outputSwitches.WriteLine(currSwitch.getInsDate());
outputSwitches.WriteLine(currSwitch.getElecTest());
outputSwitches.WriteLine(currSwitch.getPatId());
outputSwitches.WriteLine(currSwitch.getNumDevice());
}
outputSwitches.Close();
}
if (outputSwitches != null) outputSwitches.Close();
}
private void showListOfSwitches()
{
lstSwitch.Items.Clear();
foreach (Switch b in switches)
lstSwitch.Items.Add(b.getSerialNo()
+ b.getType() + b.getInsDate()
+ b.getElecTest() + b.getPatId() + b.getNumDevice());
}
My code for the search form:
private void btnSearch_Click(object sender, EventArgs e)
{
frmSearchSwitch tempSearchSwitch = new frmSearchSwitch();
tempSearchSwitch.Show();
frmkeepSwitches.Hide();
}
If using a List<T> and lambda is not possible for you then go no farther.
Here I use a List<T> for the data source of a ListBox and mocked up data as where the data comes from is not important but here I am focusing on searching on a property within a class where a select is used to index the items then the where searches in this case) for a specific item, if found the index is used to move to the item. No code present for if not located as this is easy for you to do if the code here is something that is doable for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ListBoxSearch_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var results =
((List<Item>)ListBox1.DataSource)
.Select((data, index) => new
{ Text = data.SerialNumber, Index = index })
.Where((data) => data.Text == "BB1").FirstOrDefault();
if (results != null)
{
ListBox1.SelectedIndex = results.Index;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Item>() {
new Item {Identifier = 1, SerialNumber = "AA1", Type = "A1"},
new Item {Identifier = 2, SerialNumber = "BB1", Type = "A1"},
new Item {Identifier = 3, SerialNumber = "CD12", Type = "XD1"}
};
ListBox1.DisplayMember = "DisplayText";
ListBox1.DataSource = items;
}
}
/// <summary>
/// Should be in it's own class file
/// but done here to keep code together
/// </summary>
public class Item
{
public string SerialNumber { get; set; }
public string Type { get; set; }
public int Identifier { get; set; }
public string DisplayText
{
get
{
return SerialNumber + " " + this.Type;
}
}
}
}

C# Using SoundPlayer to Pause and Resume

I am another person dabbling with C# and wanting to create a simple audio application that plays wav files loaded into the program via an upload program. My issue is that I need to get whatever audio file currently being played to pause with the track timer of the audio file being used when I start the audio file again via my Play button. I already have a global timer, 'baseTimer', that I think I can use to set the audio file, that was stopped, track duration point. However I do not know how to accomplish this nor do I really know how to use all of the mci commands yet.
I have displayed all of my code for my main application... I also have read that I may need to utilize threading, but I've also read that it would be impossible to set an audio files track duration with a thread.
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
System.Timers.Timer baseTimer = new System.Timers.Timer();
List<string> PlayList = new List<string>();
List<byte> PlayList_byte;
int soundNum = 0;
private string music_PATH { get; set; }
private string talk_PATH { get; set; }
private byte Pause_TIME { get; set; }
private string Pause_RADIO { get; set; }
bool isStopped = new bool();
bool isPaused = new bool();
[DllImport("winmm.dll")]
private static extern uint mciSendString(string command, StringBuilder returnValue, int returnLength, IntPtr winHandle);
public static int GetSoundLength(string fileName)
{
StringBuilder lengthBuf = new StringBuilder(32);
mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
mciSendString("close wave", null, 0, IntPtr.Zero);
int length = 0;
int.TryParse(lengthBuf.ToString(), out length);
return length;
}
private void SetPath()
{
music_PATH = #"..\\..\\commercial\list.txt";
talk_PATH = #"..\\..\\main\list.txt";
StreamReader myReader;
using (myReader = new StreamReader(music_PATH))
{
while (myReader.Peek() != -1)
{
string read = myReader.ReadLine();
PlayList.Add(read);
}
}
using (myReader = new StreamReader(talk_PATH))
{
while (myReader.Peek() != -1)
{
string read = myReader.ReadLine();
PlayList.Add(read);
}
myReader.Close();
}
foreach (string sound in PlayList)
{
soundNum++;
}
}
private string CurrentSound()
{
try
{
Random _randx = new Random();
int pick = _randx.Next(0, soundNum);
string currentaudio = PlayList[pick];
Pause_RADIO = currentaudio;
return currentaudio;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
return null;
}
string _SelectedSound = "";
private string _Sound(string currentradio, string pattern)
{
foreach (Match entry in Regex.Matches(currentradio, pattern))
{
_SelectedSound = entry.Value.ToString();
}
if (_SelectedSound == "music")
{
return "commercial";
}
else if (_SelectedSound == "talk")
{
return "main";
}
return null;
}
private void _SetTimer(string currentradio, string pattern)
{
baseTimer.Interval = GetSoundLength(#"..\\..\\" + pattern + #"\" + currentradio);
}
private bool isRepeat(string lastradio, string currentradio)
{
if (lastradio == currentradio)
{
return true;
}
else
{
return false;
}
}
private void baseTimerElasped(object sender, ElapsedEventArgs e)
{
Radio.FrmMain play = new Radio.FrmMain();
play.PlayPlayer();
}
private void PlayPlayer()
{
MediaPlayer wavplayer;
try
{
if (soundNum == 0)
{
SetPath();
PlayPlayer();
}
else
{
string currentradio = CurrentSound();
bool localcheck = isRepeat(_SelectedSound, currentradio);
if (localcheck == true)
{
PlayPlayer();
}
else
{
string Pattern = #"(music|talk)";
string selected = _Sound(currentradio, Pattern);
_SetTimer(currentradio, selected);
switch (selected)
{
case "commercial":
music_PATH = #"..\\..\\commercial\";
PlayList_byte = new List<byte>(File.ReadAllBytes(music_PATH + currentradio));
wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
wavplayer.Play();
baseTimer.Start();
break;
case "main":
talk_PATH = #"..\\..\\main\";
PlayList_byte = new List<byte>(File.ReadAllBytes(talk_PATH + currentradio));
wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
wavplayer.Play();
baseTimer.Start();
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + ex.StackTrace + ex.Source);
}
}
private void PausePlayer()
{
MediaPlayer wavplayer = new MediaPlayer(PlayList_byte.GetRange(0, PlayList_byte.Count).ToArray());
baseTimer.Stop();
MessageBox.Show("Count: " + PlayList_byte.Count + "Pause_TIME: " + Pause_TIME + "\nPlaylist_byte" + PlayList_byte.ToString());
try
{
switch (isPaused)
{
case false:
isPaused = true;
wavplayer.Stop();
break;
case true:
isPaused = false;
string localcheck = _Sound(Pause_RADIO, #"(music|talk)");
switch (localcheck)
{
case "commercial":
music_PATH = #"..\\..\\commercial\";
wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
break;
case "main":
talk_PATH = #"..\\..\\main\";
wavplayer.Play(PlayList_byte.GetRange(PlayList_byte.Count - Pause_TIME, PlayList_byte.Count - Pause_TIME).ToArray());
break;
}
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + ex.Data);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
switch (isStopped)
{
case false:
isStopped = true;
btnPlay.Image = Image.FromFile(#"..\\..\\Pause.png");
lblPlay.Text = "Pause";
if (isPaused == false)
{
PlayPlayer();
}
else
{
PausePlayer();
}
break;
case true:
isStopped = false;
btnPlay.Image = Image.FromFile(#"..\\..\\Play.png");
lblPlay.Text = "Play";
PausePlayer();
break;
}
baseTimer.Elapsed += new ElapsedEventHandler(baseTimerElasped);
}
private void btnNext_Click(object sender, EventArgs e)
{
PlayPlayer();
}
private void btnStop_Click(object sender, EventArgs e)
{
MediaPlayer wavplayer = new MediaPlayer();
wavplayer.Stop();
baseTimer.Stop();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnGetUpload_Click(object sender, EventArgs e)
{
Uploader FrmUpload = new Uploader();
FrmUpload.Show();
this.Hide();
}
}
class MediaPlayer
{
SoundPlayer wavplayer;
public MediaPlayer()
{
Stop();
}
public MediaPlayer(byte[] buffer)
{
MemoryStream memStream = new MemoryStream(buffer, true);
wavplayer = new SoundPlayer(memStream);
}
public void Play()
{
wavplayer.Play();
}
public void Play(byte[] buffer)
{
wavplayer.Stream.Seek(0, SeekOrigin.Begin);
wavplayer.Stream.Write(buffer, 0, buffer.Length);
wavplayer.Play();
}
public void Stop()
{
wavplayer.Stop();
}
}
Edit:
For clarity currentaudio has a file as such "music3.wav" or "talk1.wav" in it.
Super old question but just for anyone looking here's what worked for me:
double currentPos = audioplayer.CurrentPosition;
audioplayer.Play();
audioplayer.Seek(currentPos);
SoundPlayer is extremely limited, and doesn't support Pause and Resume. Are you able to use the WPF MediaElement instead? You will find it is much more powerful, supporting playing files of many types, repositioning, setting volume, pausing and resuming. You can also use it to get the file length instead of mci.

NullReferenceException WIA C#

When I run the code below I get this error
NullreferenceException was unhandled..
below is my code
private void showScannerDialog()
{
this.scanner = null;
this.imageItem = null;
this.getScanner();
WIA.CommonDialog dialog = new WIA.CommonDialog();
Items imageItems = dialog.ShowSelectItems(this.scanner, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
if (imageItems != null)
{
foreach (Item item in imageItems)
{
imageItem = item;
break;
}
}
}
thanks
// complete code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string scannerName;
private Device scanner;
private Item imageItem;
private const int ADF = 1;
private const int FLATBED = 2;
private const int DEVICE_NAME_PROPERTY_ID = 7;
private const int DOCUMENT_HANDLING_PROPERTY_ID = 3088;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
showScannerDialog();
}
public static string[] GetScannerList()
{
ArrayList scannerList = new ArrayList();
DeviceManager deviceManager = new DeviceManager();
if (deviceManager.DeviceInfos.Count == 0)
{
return new string[0]; // return an empty string array
}
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = deviceInfo.Connect();
scannerList.Add(getDeviceProperty(device, DEVICE_NAME_PROPERTY_ID));
}
}
return (string[])scannerList.ToArray(typeof(string));
}
public int Init(string scannerName)
{
this.scannerName = scannerName;
this.showScannerDialog();
if (this.imageItem == null)
{
return 0;
}
else
{
return 1;
}
}
public int Scan(string filePath)
{
Tiff tiff = new Tiff(filePath);
bool adf = false;
int numScans = 0;
ArrayList tempFiles = new ArrayList();
// determine if the scanner is set to use an ADF
string docHandlingSelect = getDeviceProperty(this.scanner, DOCUMENT_HANDLING_PROPERTY_ID);
if (docHandlingSelect != "")
{
try
{
if ((int.Parse(docHandlingSelect) & ADF) == ADF)
{
adf = true;
}
}
catch { }
}
while (true)
{
string tempFile = Path.GetTempFileName();
tempFiles.Add(tempFile);
File.Delete(tempFile);
ImageFile wiaFile = (ImageFile)imageItem.Transfer(FormatID.wiaFormatTIFF);
wiaFile.SaveFile(tempFile);
Image tempImage = Image.FromFile(tempFile);
tiff.AddImage(tempImage);
tempImage.Dispose();
numScans++;
if (!adf)
{
DialogResult result =
MessageBox.Show("Do you wish to scan another page and save it to the same file?",
"Scanner Message", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
break;
}
this.showScannerDialog();
if (this.imageItem == null)
{
break;
}
}
}
tiff.Close();
foreach (string f in tempFiles.ToArray(typeof(string)))
{
File.Delete(f);
}
Marshal.ReleaseComObject(imageItem);
if (numScans == 0)
{
throw new Exception("Nothing was scanned.");
}
return 1;
}
private void getScanner()
{
DeviceManager deviceManager = new DeviceManager();
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = deviceInfo.Connect();
if (this.scannerName == getDeviceProperty(device, DEVICE_NAME_PROPERTY_ID))
{
this.scanner = device;
}
}
}
}
private void showScannerDialog()
{
this.scanner = null;
this.imageItem = null;
this.getScanner();
WIA.CommonDialog dialog = new WIA.CommonDialog();
Items imageItems = dialog.ShowSelectItems(this.scanner, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
if (imageItems != null)
{
foreach (Item item in imageItems)
{
imageItem = item;
break;
}
}
}
private static string getDeviceProperty(Device device, int propteryID)
{
string retVal = "";
foreach (Property prop in device.Properties)
{
if (prop.PropertyID == propteryID)
{
retVal = prop.get_Value().ToString();
break;
}
}
return retVal;
}
}
}
this.scanner is set to null when you pass it to dialog.ShowSelectItems(). The function may be trying to use it without checking if it is null.

Saving to File in C#, visual studio 2010, errors

g'day guys,
i have a small error with my program where when i try to save to file an error occurs which says "A required privilege is not held by the client." I not sure how to fix this as i am running it off of my laptop which only i use and unless i have set up administrator status correctly i dont know what is going on.
I posted my code below just to be sure
Cheers.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
delegate void addlistitemcallback(string value);
public static string inputdata;
public static int MaximumSpeed, maximumRiderInput, RiderInput, Time, CurrentSpeed, DistanceTravelled, MaximumMotorOutput, MotorOutput, InputSpeed;
public static string SaveDataString;
public Thread Serial;
public static SerialPort SerialData;
public static string[] portlist = SerialPort.GetPortNames();
public static string[] SaveData = new string[4];
public static string directory = "C:\\";
public Form1()
{
Serial = new Thread(ReadData);
InitializeComponent();
int Count = 0;
for (Count = 0; Count < portlist.Length; Count++)
{
ComPortCombo.Items.Add(portlist[Count]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void StartDataButton_Click(object sender, EventArgs e)
{
SerialData = new SerialPort(ComPortCombo.Text, 19200, Parity.None, 8, StopBits.One);
SerialData.Open();
SerialData.WriteLine("P");
Serial.Start();
StartDataButton.Enabled = false;
EndDataButton.Enabled = true;
ComPortCombo.Enabled = false;
CurrentSpeed = 0;
MaximumSpeed = 0;
Time = 0;
DistanceTravelled = 0;
MotorOutput = 0;
RiderInput = 0;
SaveData[0] = "";
SaveData[1] = "";
SaveData[2] = "";
SaveData[3] = "";
SaveDataButton.Enabled = false;
if (SerialData.IsOpen)
{
ComPortStatusLabel.Text = "OPEN";
SerialData.NewLine = "/n";
SerialData.WriteLine("0");
SerialData.WriteLine("/n");
}
}
private void EndDataButton_Click(object sender, EventArgs e)
{
SerialData.Close();
SaveDataButton.Enabled = true;
//SerialData.WriteLine("1");
//SerialData.WriteLine("0");
if (!SerialData.IsOpen)
{
ComPortStatusLabel.Text = "CLOSED";
}
int i = 0;
for (i = 0; i < 4; i++)
{
if (i == 0)
{
SaveDataString = "MaximumSpeed during the Ride was = " + Convert.ToString(MaximumSpeed) + "m/h";
SaveData[i] = SaveDataString;
}
if (i == 1)
{
SaveDataString = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "m";
SaveData[i] = SaveDataString;
}
if (i == 2)
{
SaveDataString = "Maximum Rider Input Power = " + Convert.ToString(maximumRiderInput) + "Watts";
SaveData[i] = SaveDataString;
}
if (i == 3)
{
SaveDataString = "Maximum Motor Output Power = " + Convert.ToString(MaximumMotorOutput) + "Watts";
SaveData[i] = SaveDataString;
}
}
}
private void SaveDataButton_Click(object sender, EventArgs e)
{
//File.WriteAllBytes(directory + "image" + imageNO + ".txt", ); //saves the file to Disk
File.WriteAllLines("C:\\" + "BikeData.txt", SaveData);
}
public void updateSpeedtextbox(string value)
{
if (SpeedTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateSpeedtextbox);
Invoke(d, new object[] { value });
}
else
{
SpeedTextBox.Text = value;
}
}
public void updatePowertextbox(string value)
{
if (RiderInputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updatePowertextbox);
Invoke(d, new object[] { value });
}
else
{
RiderInputTextBox.Text = value;
}
}
public void updateDistancetextbox(string value)
{
if (DistanceTravelledTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateDistancetextbox);
Invoke(d, new object[] { value });
}
else
{
DistanceTravelledTextBox.Text = value;
}
}
public void updateMotortextbox(string value)
{
if (MotorOutputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateMotortextbox);
Invoke(d, new object[] { value });
}
else
{
MotorOutputTextBox.Text = value;
}
}
public void ReadData()
{
int counter = 0;
while (SerialData.IsOpen)
{
if (counter == 0)
{
try
{
InputSpeed = Convert.ToInt16(SerialData.ReadChar());
if (CurrentSpeed > MaximumSpeed)
{
MaximumSpeed = CurrentSpeed;
}
updateSpeedtextbox("Current Wheel Speed = " + Convert.ToString(InputSpeed) + "Km/h");
DistanceTravelled = DistanceTravelled + (Convert.ToInt16(InputSpeed) * Time);
updateDistancetextbox("Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km");
}
catch (Exception) { }
}
if (counter == 1)
{
try
{
RiderInput = Convert.ToInt16(SerialData.ReadChar());
if (RiderInput > maximumRiderInput)
{
maximumRiderInput = RiderInput;
}
updatePowertextbox("Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts");
}
catch (Exception) { }
}
if (counter == 2)
{
try
{
MotorOutput = Convert.ToInt16(SerialData.ReadChar());
if (MotorOutput > MaximumMotorOutput)
{
MaximumMotorOutput = MotorOutput;
}
updateMotortextbox("Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts");
}
catch (Exception) { }
}
counter++;
if (counter == 3)
{
counter = 0;
}
}
}
private void Form1_Closed(object sender, EventArgs e)
{
if (SerialData.IsOpen)
{
SerialData.Close();
}
}
private void ComPortCombo_SelectedIndexChanged(object sender, EventArgs e)
{
StartDataButton.Enabled = true;
}
private void DistanceTravelledTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
You probably don't have write access to C:\. Try changing the save path to "C:\Users\{YouName}\Documents\BikeData.txt" instead.
Or start Visual Studio with administrative privileges by right clicking on its icon and choosing "Run as Administrator"
File.WriteAllLines("C:\" + "BikeData.txt", SaveData);
File.WriteAllLine(string,string[]), through "SecurityException" when user does not have rights to write in a particular directrory or drive so you have to give write permission, refer this link File.WriteAllLines

Categories