Search Results

Search found 3977 results on 160 pages for 'filename'.

Page 17/160 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • How I can export a datatable to MS word 2007, excel 2007,csv from asp.net?

    - by bala3569
    Hi, I am using the below code to Export DataTable to MS Word,Excel,CSV format & it's working fine. But problem is that this code export to MS Word 2003,Excel 2003 version. I need to Export my DataTable to Word 2007,Excel 2007,CSV because I am supposed to handle more than 100,000 records at a time and as we know Excel 2003 supports for only 65,000 records. Please help me out if you know that how to export DataTable or DataSet to MS Word 2007,Excel 2007. public static void Convertword(DataTable dt, HttpResponse Response,string filename) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.word"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView(); dg.DataSource = dt; dg.DataBind(); dg.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); } public static void Convertexcel(DataTable dt, HttpResponse Response, string filename) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.DataSource = dt; dg.DataBind(); dg.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); } public static void ConvertCSV(DataTable dataTable, HttpResponse Response, string filename) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "Application/x-msexcel"; StringBuilder sb = new StringBuilder(); if (dataTable.Columns.Count != 0) { foreach (DataColumn column in dataTable.Columns) { sb.Append(column.ColumnName + ','); } sb.Append("\r\n"); foreach (DataRow row in dataTable.Rows) { foreach (DataColumn column in dataTable.Columns) { if(row[column].ToString().Contains(',')==true) { row[column] = row[column].ToString().Replace(",", ""); } sb.Append(row[column].ToString() + ','); } sb.Append("\r\n"); } } Response.Write(sb.ToString()); Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); }

    Read the article

  • Android - Resuming application state - SL4A

    - by toyotajon93
    please dont harpoon me for a noob-ish question. I am working on an android application using SL4A, when my application starts it runs in the background while the script is being executed. I'm not sure where to start but each time I click my icon, it re-starts my application. I have tried using different launchmodes with nothing different happening. I'm thinking it has to do with the OnCreate code, and the setting of the notification. I need help saving my application state and then resuming on either re-click of icon or click from notification bar. I've tried everything had to turn here for help. I am not a pro at android programming by any means. Thanks guys, be gentle ;) Public void onCreate() { super.onCreate(); mInterpreterConfiguration = ((BaseApplication) getApplication()) .getInterpreterConfiguration(); } @Override public void onStart(Intent intent, final int startId) { super.onStart(intent, startId); String fileName = Script.getFileName(this); Interpreter interpreter = mInterpreterConfiguration .getInterpreterForScript(fileName); if (interpreter == null || !interpreter.isInstalled()) { mLatch.countDown(); if (FeaturedInterpreters.isSupported(fileName)) { Intent i = new Intent(this, DialogActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(Constants.EXTRA_SCRIPT_PATH, fileName); startActivity(i); } else { Log .e(this, "Cannot find an interpreter for script " + fileName); } stopSelf(startId); return; } // Copies script to internal memory. fileName = InterpreterUtils.getInterpreterRoot(this).getAbsolutePath() + "/" + fileName; File script = new File(fileName); // TODO(raaar): Check size here! if (!script.exists()) { script = FileUtils.copyFromStream(fileName, getResources() .openRawResource(Script.ID)); } copyResourcesToLocal(); // Copy all resources if (Script.getFileExtension(this) .equals(HtmlInterpreter.HTML_EXTENSION)) { HtmlActivityTask htmlTask = ScriptLauncher.launchHtmlScript(script, this, intent, mInterpreterConfiguration); mFacadeManager = htmlTask.getRpcReceiverManager(); mLatch.countDown(); stopSelf(startId); } else { mProxy = new AndroidProxy(this, null, true); mProxy.startLocal(); mLatch.countDown(); ScriptLauncher.launchScript(script, mInterpreterConfiguration, mProxy, new Runnable() { @Override public void run() { mProxy.shutdown(); stopSelf(startId); } }); } } RpcReceiverManager getRpcReceiverManager() throws InterruptedException { mLatch.await(); if (mFacadeManager==null) { // Facade manage may not be available on startup. mFacadeManager = mProxy.getRpcReceiverManagerFactory() .getRpcReceiverManagers().get(0); } return mFacadeManager; } @Override protected Notification createNotification() { Notification notification = new Notification(R.drawable.script_logo_48, this.getString(R.string.loading), System.currentTimeMillis()); // This contentIntent is a noop. PendingIntent contentIntent = PendingIntent.getService(this, 0, new Intent(), 0); notification.setLatestEventInfo(this, this.getString(R.string.app_name), this.getString(R.string.loading), contentIntent); notification.flags = Notification.FLAG_ONGOING_EVENT; return notification; }

    Read the article

  • Video Recording Not Working in ICS

    - by Nirav Ranpara
    I have implement code Record video in Android Phone . This code is working in 2.2 , 2.3 . not in ICS But when I checked in ICS code is not working ? here I posted code and xml file. videorecord.java import java.io.File; import java.io.IOException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Camera; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Environment; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class videorecord extends Activity{ SharedPreferences.Editor pre; String filename; CountDownTimer t; private Camera myCamera; private MyCameraSurfaceView myCameraSurfaceView; private MediaRecorder mediaRecorder; Integer cnt=0; LinearLayout myButton; TextView myButton1; SurfaceHolder surfaceHolder; boolean recording; private TextView txtcount; private ImageView btnplay; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); recording = false; setContentView(R.layout.videorecord); init(); myCamera = getCameraInstance(); if(myCamera == null){ } myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera); FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview); Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); myCameraSurfaceView.setLayoutParams(new LinearLayout.LayoutParams(width, height-60)); myCameraPreview.addView(myCameraSurfaceView); myButton = (LinearLayout)findViewById(R.id.mybutton); btnplay.setOnClickListener(myButtonOnClickListener); } private void init() { txtcount = (TextView) findViewById(R.id.txtcounter); //myButton1 = (TextView) findViewById(R.id.mybutton1); btnplay = (ImageView)findViewById(R.id.btnplay); t = new CountDownTimer( Long.MAX_VALUE , 1000) { @Override public void onTick(long millisUntilFinished) { cnt++; String time = new Integer(cnt).toString(); long millis = cnt; int seconds = (int) (millis / 60); int minutes = seconds / 60; seconds = seconds % 60; txtcount.setText(String.format("%d:%02d:%02d", minutes, seconds,millis)); } @Override public void onFinish() { } }; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { if(recording) { new AlertDialog.Builder(videorecord.this).setTitle("Do you want to save Video ?") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { filename(); //finish(); } }).setNegativeButton("Cancle", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).show(); } else { if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Intent homeIntent= new Intent(Intent.ACTION_MAIN); //homeIntent.addCategory(Intent.CATEGORY_HOME); //homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //startActivity(homeIntent); //this.finishActivity(1); finish(); } //moveTaskToBack(true); // finish(); return super.onKeyDown(keyCode, event); } } else { // Toast.makeText(getApplicationContext(), "asd", Toast.LENGTH_LONG).show(); android.os.Process.killProcess(android.os.Process.myPid()) ; } return super.onKeyDown(keyCode, event); } ImageView.OnClickListener myButtonOnClickListener = new ImageView.OnClickListener(){ public void onClick(View v) { if(recording){ Log.e("Record error", "error in recording ."); mediaRecorder.stop(); t.cancel(); filename(); releaseMediaRecorder(); }else{ releaseCamera(); Log.e("Record Stop error", "error in recording ."); // if(!prepareMediaRecorder()){ prepareMediaRecorder(); finish(); } mediaRecorder.start(); recording = true; // myButton1.setText("STOP Recording"); // btnplay.setImageResource(android.R.drawable.ic_media_pause); btnplay.setImageResource(R.drawable.stoprec); t.start(); } }}; private Camera getCameraInstance(){ Camera c = null; try { c = Camera.open(); } catch (Exception e){ } return c; } private void filename() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Save Video"); alert.setMessage("Enter File Name"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(input.getText().length()>=1) { filename = input.getText().toString(); File sdcard = new File(Environment.getExternalStorageDirectory() + "/VideoRecord"); File from = new File(sdcard,"null.mp4"); File to = new File(sdcard,filename+".mp4"); from.renameTo(to); SharedPreferences sp = videorecord.this.getSharedPreferences("data", MODE_WORLD_WRITEABLE); pre = sp.edit(); pre.clear(); pre.commit(); pre.putString("lastvideo", filename+".mp4"); pre.commit(); //btnplay.setImageResource(android.R.drawable.ic_media_play); btnplay.setImageResource(R.drawable.startrec); // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class); // startActivity(intent); Intent myIntent = new Intent(getApplicationContext(), StopVidoWatch_Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(myIntent); } else { filename(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class); // startActivity(intent); File file = new File(Environment.getExternalStorageDirectory() + "/VideoRecord/null.mp4"); //boolean deleted = file.delete(); file.delete(); finish(); } }); alert.show(); } private boolean prepareMediaRecorder(){ myCamera = getCameraInstance(); mediaRecorder = new MediaRecorder(); myCamera.unlock(); mediaRecorder.setCamera(myCamera); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); File folder = new File(Environment.getExternalStorageDirectory() + "/VideoRecord"); boolean success = false; if (!folder.exists()) { success = folder.mkdir(); } if (!success) { } else { } mediaRecorder.setOutputFile("/sdcard/VideoRecord/"+filename+".mp4"); mediaRecorder.setMaxDuration(60000); mediaRecorder.setMaxFileSize(5000000); Display display = getWindowManager().getDefaultDisplay(); int width = display.getHeight(); int height = display.getWidth(); String s = new String(); s= s.valueOf(width); String s1 = new String(); s1= s1.valueOf(height); // Toast.makeText(videorecord.this, "Width : " + s , Toast.LENGTH_LONG).show(); // Toast.makeText(videorecord.this, "Height : " + s1 , Toast.LENGTH_LONG).show(); mediaRecorder.setVideoSize(height, width); mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface()); try { mediaRecorder.prepare(); } catch (IllegalStateException e) { releaseMediaRecorder(); return false; } catch (IOException e) { releaseMediaRecorder(); return false; } return true; } @Override protected void onPause() { super.onPause(); releaseMediaRecorder(); releaseCamera(); } private void releaseMediaRecorder() { if (mediaRecorder != null) { mediaRecorder.reset(); mediaRecorder.release(); mediaRecorder = null; myCamera.lock(); } } private void releaseCamera(){ if (myCamera != null){ myCamera.release(); myCamera = null; } } public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{ private SurfaceHolder mHolder; private Camera mCamera; public MyCameraSurfaceView(Context context, Camera camera) { super(context); mCamera = camera; mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceChanged(SurfaceHolder holder, int format, int weight, int height) { if (mHolder.getSurface() == null){ return; } try { mCamera.stopPreview(); } catch (Exception e){ } try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e){ } } public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { } } public void surfaceDestroyed(SurfaceHolder holder) { } } } videorecord.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout android:id="@+id/videoview" android:layout_width="fill_parent" android:layout_height="fill_parent"></FrameLayout> <LinearLayout android:id="@+id/mybutton" android:layout_width="fill_parent" android:layout_marginBottom="0dip" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_weight="0" > <!-- <TextView android:text="START Recording" android:id="@+id/mybutton1" android:layout_height="wrap_content" android:layout_width="wrap_content" style="@style/savestyle" android:layout_weight="1" android:gravity="left" > </TextView> --> <ImageView android:layout_height="wrap_content" android:id="@+id/btnplay" android:padding="5dip" android:background="#A0000000" android:textColor="#ffffffff" android:layout_width="wrap_content" android:src="@drawable/startrec" /> </LinearLayout> <TextView android:text="00:00:00" android:id="@+id/txtcounter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right|bottom" android:padding="5dip" android:background="#A0000000" android:textColor="#ffffffff" /> </FrameLayout> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/bgcolor" > <LinearLayout android:layout_above="@+id/mybutton" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout> </RelativeLayout> </LinearLayout>

    Read the article

  • How to edit item in a listbox shown from reading a .csv file?

    - by Shuvo
    I am working in a project where my application can open a .csv file and read data from it. The .csv file contains the latitude, longitude of places. The application reads data from the file shows it in a static map and display icon on the right places. The application can open multiple file at a time and it opens with a new tab every time. But I am having trouble in couple of cases When I am trying to add a new point to the .csv file opened. I am able to write new point on the same file instead adding a new point data to the existing its replacing others and writing the new point only. I cannot use selectedIndexChange event to perform edit option on the listbox and then save the file. Any direction would be great. 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; namespace CourseworkExample { public partial class Form1 : Form { public GPSDataPoint gpsdp; List<GPSDataPoint> data; List<PictureBox> pictures; List<TabPage> tabs; public static int pn = 0; private TabPage currentComponent; private Bitmap bmp1; string[] symbols = { "hospital", "university" }; Image[] symbolImages; ListBox lb = new ListBox(); string name = ""; string path = ""; public Form1() { InitializeComponent(); data = new List<GPSDataPoint>(); pictures = new List<PictureBox>(); tabs = new List<TabPage>(); symbolImages = new Image[symbols.Length]; for (int i = 0; i < 2; i++) { string location = "data/" + symbols[i] + ".png"; symbolImages[i] = Image.FromFile(location); } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; lb.Width = 300; int selectedindex = lb.SelectedIndex; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); } } private void openToolStripMenuItem_Click_1(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; ListBox lb = new ListBox(); lb.Width = 300; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); MessageBox.Show(data.ToString()); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void addBtn_Click(object sender, EventArgs e) { string wayName = nameTxtBox.Text; float wayLat = Convert.ToSingle(latTxtBox.Text); float wayLong = Convert.ToSingle(longTxtBox.Text); float wayEle = Convert.ToSingle(elevTxtBox.Text); WayPoint wp = new WayPoint(wayName, wayLat, wayLong, wayEle); GPSDataPoint gdp = new GPSDataPoint(); data = new List<GPSDataPoint>(); gdp.Add(wp); lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); lb.Refresh(); StreamWriter sr = new StreamWriter(name); sr.Write(lb); sr.Close(); DialogResult result = MessageBox.Show("Save in New File?","Save", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = "default.csv"; DialogResult saveResult = saveDialog.ShowDialog(); if (saveResult == DialogResult.OK) { sr = new StreamWriter(saveDialog.FileName, true); sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } } else { // sr = new StreamWriter(name, true); // sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } MessageBox.Show(name + path); } } } GPSDataPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace CourseworkExample { public class GPSDataPoint { private float[] bounds; private List<WayPoint> dataList; public GPSDataPoint() { dataList = new List<WayPoint>(); } internal void setBounds(string p) { string[] b = p.Split(','); bounds = new float[b.Length]; for (int i = 0; i < b.Length; i++) { bounds[i] = Convert.ToSingle(b[i]); } } public float[] Bounds { get { return bounds; } } internal void addWaypoint(string s) { WayPoint wp = new WayPoint(s); dataList.Add(wp); } public WayPoint getWayPoint(int i) { if (i < dataList.Count) { return dataList[i]; } else return null; } public List<WayPoint> DataList { get { return dataList; } } internal void Add(WayPoint wp) { dataList.Add(wp); } } } WayPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CourseworkExample { public class WayPoint { private string name; private float ele; private float latitude; private float longitude; private string sym; public WayPoint(string name, float latitude, float longitude, float elevation) { this.name = name; this.latitude = latitude; this.longitude = longitude; this.ele = elevation; } public WayPoint() { name = "no name"; ele = 3.5F; latitude = 3.5F; longitude = 0.0F; sym = "no symbol"; } public WayPoint(string s) { string[] bits = s.Split(','); name = bits[0]; longitude = Convert.ToSingle(bits[2]); latitude = Convert.ToSingle(bits[1]); if (bits.Length > 4) sym = bits[4]; else sym = ""; try { ele = Convert.ToSingle(bits[3]); } catch (Exception e) { ele = 0.0f; } } public float Longitude { get { return longitude; } set { longitude = value; } } public float Latitude { get { return latitude; } set { latitude = value; } } public float Ele { get { return ele; } set { ele = value; } } public string Name { get { return name; } set { name = value; } } public string Sym { get { return sym; } set { sym = value; } } } } .csv file data birthplace.png 51.483788,-0.351906,51.460745,-0.302982 Born Here,51.473805,-0.32532,-,hospital Danced here,51,483805,-0.32532,-,hospital

    Read the article

  • PycURL RESUME_FROM

    - by excid3
    I can't seem to get the RESUME_FROM option to work. Here's some example code that I have been testing with: import os import pycurl import sys def progress(total, existing, upload_t, upload_d): try: frac = float(existing)/float(total) except: frac = 0 sys.stdout.write("\r%s %3i%%" % ("file", frac*100) ) url = "http://launchpad.net/keryx/stable/0.92/+download/keryx_0.92.4.tar.gz" filename = url.split("/")[-1].strip() def test(debug_type, debug_msg): print "debug(%d): %s" % (debug_type, debug_msg) c = pycurl.Curl() c.setopt(pycurl.URL, url) c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) # Setup writing if os.path.exists(filename): f = open(filename, "ab") c.setopt(pycurl.RESUME_FROM, os.path.getsize(filename)) else: f = open(filename, "wb") c.setopt(pycurl.WRITEDATA, f) #c.setopt(pycurl.VERBOSE, 1) c.setopt(pycurl.DEBUGFUNCTION, test) c.setopt(pycurl.NOPROGRESS, 0) c.setopt(pycurl.PROGRESSFUNCTION, progress) c.perform()

    Read the article

  • NAnt build issues with Mono

    - by calmcajun
    I am trying to build a Mono project using NAnt but I get the error listed below. I have tried altering the environment variable PKG_CONFIG_PATH to include the path leading to the file: mono.pc but that does not seem to work. Failed to initialize the 'Mono 3.5 Profile' (mono-3.5) target framework.: NAnt.Core.BuildException: Failed to initialize the 'Mono 3.5 Profile' (mono-3.5) target framework. ---> Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/.: NAnt.Core.BuildException: Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. at NAnt.Core.Tasks.FailTask.ExecuteTask () [0x00000] in <filename unknown>:0 at NAnt.Core.Task.Execute () [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at NAnt.Core.FrameworkInfo.Init () [0x00000] in <filename unknown>:0 at NAnt.Core.FrameworkInfo.Validate () [0x00000] in <filename unknown>:0 at NAnt.Core.ProjectSettingsLoader.ConfigureRuntimeFramework () [0x00000] in <filename unknown>:0

    Read the article

  • Downloading a Directory Tree with FTPLIB

    - by Anthony Lemmer
    I'd like to download a directory and all of its contents to the local HD. Here's the code I have thus far (crashes if there's a sub-directory, else grabs all the files): import ftplib import configparser import os def runBackups(): #Load INI filename = 'connections.ini' config = configparser.SafeConfigParser() config.read(filename) connections = config.sections() i = 0 while i < len(connections): #Load Settings uri = config.get(connections[i], "uri") username = config.get(connections[i], "username") password = config.get(connections[i], "password") backupPath = config.get(connections[i], "backuppath") archiveTo = config.get(connections[i], "archiveto") #Start Back-ups ftp = ftplib.FTP(uri) ftp.login(username, password) ftp.set_debuglevel(2) ftp.cwd(backupPath) files = ftp.nlst() for filename in files: ftp.retrbinary('RETR %s' % filename, open(os.path.join(archiveTo, filename), 'wb').write) ftp.quit() i += 1 print() print("Back-ups complete.") print()

    Read the article

  • Copying part of a string in C

    - by wolfPack88
    This seems like it should be really simple, but for some reason, I'm not getting it to work. I have a string called seq, which looks like this: ala ile val I want to take the first 3 characters and copy them into a different string. I use the command: memcpy(fileName, seq, 3 * sizeof(char)); That should make fileName = "ala", right? But for some reason, I get fileName = "ala9". I'm currently working around it by just saying fileName[4] = '\0', but was wondering why I'm getting that 9. Note: After changing seq to ala ile val ser and rerunning the same code, fileName becomes "alaK". Not 9 anymore, but still an erroneous character.

    Read the article

  • How can I get a file's upload size using simple Javascript?

    - by Pankaj Khurana
    I have upload file functionality on one of the page. I check for the extension of the file using JavaScript. Now i want to restrict the user from uploading file greater than 1 MB. Is there any way i can check the file upload size using JavaScript. My code currently look like this: <script language="JavaScript"> function validate() { var filename = document.getElementById("txtChooseFile").value; var ext = getExt(filename); if(ext == "txt" || ext == "csv") return true; alert("Please upload Text files only."); return false; } function getExt(filename) { var dot_pos = filename.lastIndexOf("."); if(dot_pos == -1) return ""; return filename.substr(dot_pos+1).toLowerCase(); } </script>

    Read the article

  • The operation has timed out

    - by np
    We shave this code which result in timeout when downlaoding the file programatically: System.Net.WebClient Client = new System.Net.WebClient(); if (!File.Exists(fileName)) { Client.DownloadFile(downloadLink, fileName); HtFilesSuccessfullyDownloaded[fileName] = fileName; string SuccessfullyDownloadedFiles = Path.Combine(dirName, "SuccessfullyDownloadedFiles.txt"); File.AppendAllText(SuccessfullyDownloadedFiles, Environment.NewLine + fileName); } It looks like when the files are large we are getting the timeout error when DownloadFile method is called. We have added the followign in web.config but it does not look like it helps: <httpRuntime maxRequestLength="1048576" executionTimeout="3600" /> Please let me know if you have any suggestions.

    Read the article

  • Adapting methods which return true/false

    - by James P.
    What's the best practise when adapting C-style functions which return a true/false to Java? Here's a simple method to illustrate where the problem lies. public static boolean fileNameEndsWithExtension( String filename, String fileExtension) { return filename.endsWith( fileExtension ); } Note that there's probably a more elegant way of filtering files (feel free to comment on this). Anyway, if filename is a null value, does one: Return a false if filename is null? If so, how does one go about distinguishing between the case where filename is null and the case where the String or file name doesn't end with a given file extension? Change the return type to the wrapper class Boolean which allows a null value. Throw an Exception and force the programmer to make sure that a null value is never passed to the method? Use another solution?

    Read the article

  • VBScript Permission Denied on CopyFile

    - by Chris
    I'm running a VBScript in SQL Agent but I get a 'Permission Denied' on line 34 (the first copy attempt). I've run this script outside SQL Agent with no problems Function Main() Const SourceDrive As String = "X:\" Dim fso Dim Today Dim FileName Dim FromFile Dim FromDrive Dim ArchivePath Set fso = CreateObject("Scripting.FileSystemObject") Today = Format(Now, "yyyyMMdd") 'To add more sources just add them to the array list Dim Sources() As Variant Sources() = Array("Item1", _ "Item2") 'To add more targets just add them to the array list Dim Targets() As Variant Targets() = Array("C:\Users\myalias\Desktop\MyToFolder", _ "C:\Users\myalias\Desktop\MyToFolder2") For i = 0 To UBound(Sources) FileName = "WebSurveyAlertCallbacks_" & Sources(i) & "_" & Today & ".xls" FromDrive = fso.BuildPath(SourceDrive, Sources(i)) FromFile = fso.BuildPath(FromDrive, FileName) ArchivePath = fso.BuildPath(FromDrive, "Archive") If fso.FileExists(FromFile) Then For t = 0 To UBound(Targets) fso.CopyFile FromFile, fso.BuildPath(Targets(t), FileName), True Next fso.CopyFile FromFile, fso.BuildPath(ArchivePath, FileName), True fso.DeleteFile FromFile End If Next Set fso = Nothing Main = DTSTaskExecResult_Success End Function

    Read the article

  • Attempted to perform an unauthorized operation

    - by Lefteris Gkinis
    Now I use the following code: Public Function SetACL(ByVal filename As String, ByVal account As String, ByVal sender As Object, ByVal e As System.EventArgs) As Boolean Try Dim rule As FileSystemAccessRule = New FileSystemAccessRule(account, FileSystemRights.Write, AccessControlType.Allow) Dim fp As PermissionSet = New PermissionSet(Permissions.PermissionState.Unrestricted) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Read, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Write, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.PathDiscovery, filename)) fp.Assert() Dim di As DirectoryInfo = New DirectoryInfo(Path.GetDirectoryName(filename)) SetACL = False Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) security.ModifyAccessRule(AccessControlModification.Add, rule, SetACL) di.SetAccessControl(security) Return SetACL Catch ex As Exception MessageBox.Show(ex.Message, "Set Security Sub", MessageBoxButtons.OK, MessageBoxIcon.Stop) Finalize() End Try End Function The Error of 'Attempted to perform an unauthorized operation' comes when i'm trying to execute the instraction Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) Please if anybody knows why that error comes here to respond

    Read the article

  • I need to rename a file in VBA, but getting "File Not Found" when it's clearly there!

    - by Karl
    Help! I'm getting a File Not Found error when trying to rename a file w/a variable. The variable is string. I can look at the variable and it's the exact filename that is there, but when I run the code, it says not found! Dim filePath, fileName, absPath, newPath As String filePath = "P:\Automated\" fileName = MySite.GetResult absPath = filePath & fileName newPath = "P:\Automated\NEW.csv" 'The following is a rename from CuteFTP Pro COM Object: '(Getting the same result from this and the below "Name". 'MySite.LocalRename "P:\Automated\" & fileName, "P:\Automated\NEW.csv" Name absPath As newPath

    Read the article

  • MySQL Update Statement + File Upload

    - by Jason Sweet
    Greetings! Been staring at this all day and can't seem to figure out why my update statement fails to update the field 'image_filename': $fileName = $_FILES['image_filename']; if($fileName["name"] <> ""){ $imageFile = $fileName['name']; $destination = "../../../../assets/resources/images/".$fileName['name']; move_uploaded_file($fileName['name'], $destination); } $updateSQL = sprintf("UPDATE content SET image_filename='$imageFile' WHERE id=%s", GetSQLValueString($_POST['resource_id'], "int")); mysql_select_db($database_conn_talent, $conn_talent); $Result1 = mysql_query($updateSQL, $conn_talent) or die(mysql_error()); Can a SQL pro tell me what I"m missing? Much thanks in advance for your feedback!

    Read the article

  • File.Exists() returns false, but not in debug

    - by Tor Haugen
    I'm being completely confused here folks, My code throws an exception because File.Exists() returns false public override sealed TCargo ReadFile(string fileName) { if (!File.Exists(fileName)) { throw new ArgumentException("Provided file name does not exist", "fileName"); } Visual studio breaks at the throw statement, and I immediately check the value of File.Exists(fileName) in the immediate window. It returns true. When I drag the breakpoint back up to the if statement and execute it again, it throws again. fileName is an absolute path to a file. I'm not creating the file, nor writing to it (it's there all along). If I paste the path into the open dialog in Notepad, it reads the file without problems. The code is executing in a background worker. It's the only complicating factor I can think of. I am positive the file has not been opened already, either in the worker thread or elsewhere. What's going on here?

    Read the article

  • How to open a file with chinese name in python.

    - by mahendraliya
    I am trying to open a file in "w" mode with "open()" function in python. The filename is : ?????.jpg. The open function fails with this filename but succeeds with normal files. How can I open a file with names which are not in English in python? My code is as follows: try: filename = urllib.quote(filename.encode('utf-8')) destination = open(filename, 'w') yield("<br>Obtained the file reference") except: yield("<br>Error while opening the file") I always get "Error while opening the file" for non-english filenames. Thanks in advance.

    Read the article

  • passing dynamic values in callback method

    - by swastican
    is there a way to pass dynamic values to callback function in js or jquery or nodejs. for(var i = 0; i < 10; i++) { filename = 'file'+i+'.html'; request(url, function(error, response, body) { test(error, response, body, filename); }); function test(error, response, body, filename) { console.log('file name ' + filename); if(response.statusCode == 200){ console.log('done'); } } I refered this so article for passing values to callback function. link: [JavaScript: Passing parameters to a callback function the output always seems to be 9 How can i pass values dynamically? The callback function always refers the last value of filename.

    Read the article

  • deleting unaccessed files using python

    - by damon
    My django app parses some files uploaded by the user.It is possible that the file uploaded by the user may remain in the server for a long time ,without it being parsed by the app.This can increase in size if a lot of users upload a lot of files. I need to delete those files not recently parsed by the app -say not accessed for last 24 hours.I tried like this import os import time dirname = MEDIA_ROOT+my_folder filenames = os.listdir(dirname) filenames = [os.path.join(dirname,filename) for filename in filenames] for filename in filenames: last_access = os.stat(filename).st_atime #secs since epoch rtime = time.asctime(time.localtime(last_access)) print filename+'----'+rtime This shows the last accessed times for each file..But I am not sure how I can test if the file access time was within the last 24 hours..Can somebody help me out?

    Read the article

  • Rails: saving a string on an object -- syntax problem?

    - by Veep
    Hey there, I am trying to write a simple function to clean a filename string and update the object. When I save a test string it works, but when I try to save the string variable I've created, nothing happens. But when I return the string, the output seems to be correct! What am I missing? def clean_filename clean_name = filename clean_name.gsub! /^.*(\\|\/)/, '' clean_name.gsub! /[^A-Za-z0-9\.\-]/, '_' clean_name.gsub!(/\_+/, ' ') #update_attribute(:filename, "test") #<-- correctly sets filename to test #update_attribute(:filename, clean_name) #<-- no effect????? WTF #return clean_name <-- seems to returns the correct string end Thank you very much.

    Read the article

  • Creating PDF documents dynamically using Umbraco and XSL-FO part 2

    - by Vizioz Limited
    Since my last post I have made a few modifications to the PDF generation, the main one being that the files are now dynamically renamed so that they reflect the name of the case study instead of all being called PDF.PDF which was not a very helpful filename, I just wanted to get something live last week, so decided that something was better than nothing :)The issue with the filenames comes down to the way that the PDF's are being generated by using an alternative template in Umbraco, this means that all you need to do is add " /pdf " to the end of a case study URL and it will create a PDF version of the case study. The down side is that your browser will merrily download the file and save it as PDF.PDF because that is the name of the last part of the URL.What you need to do is set the content-disposition header to be equal to the name you would like the file use, Darren Ferguson mentioned this on the Change the name of the PDF forum post.We have used the same technique for downloading dynamically generated excel files, so I thought it would be useful to create a small macro to set both this header and also to set the caching headers to prevent any caching issues, I think in the past we have experienced all possible issues, including various issues where IE behaves differently to other browsers when you are using SSL and so the below code should work in all situations!The template for the PDF alternative template is very simple:<%@ Master Language="C#" MasterPageFile="~/umbraco/masterpages/default.master" AutoEventWireup="true" %><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderDefault" runat="server"> <umbraco:Macro Alias="PDFHeaders" runat="server"></umbraco:Macro> <umbraco:Macro xsl="FO-CaseStudy.xslt" Alias="PDFXSLFO" runat="server"></umbraco:Macro></asp:Content>The following code snippet is the XSLT macro that simply creates our file name and then passes the file name into the helper function:<xsl:template match="/"> <xsl:variable name="fileName"> <xsl:text>Vizioz_</xsl:text> <xsl:value-of select="$currentPage/@nodeName" /> <xsl:text>_case_study.pdf</xsl:text> </xsl:variable> <xsl:value-of select="Vizioz.Helper:AddDocumentDownloadHeaders('application/pdf', $fileName)"/> </xsl:template>And the following code is the helper function that clears the current response and adds all the appropriate headers:public static void AddDocumentDownloadHeaders(string contentType, string fileName){ HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; response.Clear(); response.ClearHeaders(); if (request.IsSecureConnection & request.Browser.Browser == "IE") { // Don't use the caching headers if the browser is IE and it's a secure connection // see: http://support.microsoft.com/kb/323308 } else { // force not using the cache response.AppendHeader("Cache-Control", "no-cache"); response.AppendHeader("Cache-Control", "private"); response.AppendHeader("Cache-Control", "no-store"); response.AppendHeader("Cache-Control", "must-revalidate"); response.AppendHeader("Cache-Control", "max-stale=0"); response.AppendHeader("Cache-Control", "post-check=0"); response.AppendHeader("Cache-Control", "pre-check=0"); response.AppendHeader("Pragma", "no-cache"); response.Cache.SetCacheability(HttpCacheability.NoCache); response.Cache.SetNoStore(); response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); } response.AppendHeader("Expires", DateTime.Now.AddMinutes(-1).ToLongDateString()); response.AppendHeader("Keep-Alive", "timeout=3, max=993"); response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\""); response.ContentType = contentType;}I will write another blog soon with some more details about XSL-FO and how to create the PDF's dynamically.Please do re-tweet if you find this interest :)

    Read the article

  • sp_send_dbmail attach files stored as varbinary in database

    - by Mindstorm Interactive
    I have a two part question relating to sending query results as attachments using sp_send_dbmail. Problem 1: Only basic .txt files will open. Any other format like .pdf or .jpg are corrupted. Problem 2: When attempting to send multiple attachments, I receive one file with all file names glued together. I'm running SQL Server 2005 and I have a table storing uploaded documents: CREATE TABLE [dbo].[EmailAttachment]( [EmailAttachmentID] [int] IDENTITY(1,1) NOT NULL, [MassEmailID] [int] NULL, -- foreign key [FileData] [varbinary](max) NOT NULL, [FileName] [varchar](100) NOT NULL, [MimeType] [varchar](100) NOT NULL I also have a MassEmail table with standard email stuff. Here is the SQL Send Mail script. For brevity, I've excluded declare statements. while ( (select count(MassEmailID) from MassEmail where status = 20 )>0) begin select @MassEmailID = Min(MassEmailID) from MassEmail where status = 20 select @Subject = [Subject] from MassEmail where MassEmailID = @MassEmailID select @Body = Body from MassEmail where MassEmailID = @MassEmailID set @query = 'set nocount on; select cast(FileData as varchar(max)) from Mydatabase.dbo.EmailAttachment where MassEmailID = '+ CAST(@MassEmailID as varchar(100)) select @filename = '' select @filename = COALESCE(@filename+ ',', '') +FileName from EmailAttachment where MassEmailID = @MassEmailID exec msdb.dbo.sp_send_dbmail @profile_name = 'MASS_EMAIL', @recipients = '[email protected]', @subject = @Subject, @body =@Body, @body_format ='HTML', @query = @query, @query_attachment_filename = @filename, @attach_query_result_as_file = 1, @query_result_separator = '; ', @query_no_truncate = 1, @query_result_header = 0; update MassEmailset status= 30,SendDate = GetDate() where MassEmailID = @MassEmailID end I am able to successfully read files from the database so I know the binary data is not corrupted. .txt files only read when I cast FilaData to varchar. But clearly original headers are lost. It's also worth noting that attachment file sizes are different than the original files. That is most likely due to improper encoding as well. So I'm hoping there's a way to create file headers using the stored mimetype, or some way to include file headers in the binary data? I'm also not confident in the values of the last few parameters, and I know coalesce is not quite right, because it prepends the first file name with a comma. But good documentation is nearly impossible to find. Please help!

    Read the article

  • Why is WCF Stream response getting corrupted on write to disk?

    - by Alvin S
    I am wanting to write a WCF web service that can send files over the wire to the client. So I have one setup that sends a Stream response. Here is my code on the client: private void button1_Click(object sender, EventArgs e) { string filename = System.Environment.CurrentDirectory + "\\Picture.jpg"; if (File.Exists(filename)) File.Delete(filename); StreamServiceClient client = new StreamServiceClient(); int length = 256; byte[] buffer = new byte[length]; FileStream sink = new FileStream(filename, FileMode.CreateNew, FileAccess.Write); Stream source = client.GetData(); int bytesRead; while ((bytesRead = source.Read(buffer,0,length))> 0) { sink.Write(buffer,0,length); } source.Close(); sink.Close(); MessageBox.Show("All done"); } Everything processes fine with no errors or exceptions. The problem is that the .jpg file that is getting transferred is reported as being "corrupted or too large" when I open it. What am I doing wrong? On the server side, here is the method that is sending the file. public Stream GetData() { string filename = Environment.CurrentDirectory+"\\Chrysanthemum.jpg"; FileStream myfile = File.OpenRead(filename); return myfile; } I have the server configured with basicHttp binding with Transfermode.StreamedResponse.

    Read the article

  • MonoTouch: using embedded resx files on iPhone build

    - by bright
    I'm able to load and access resx files in Simulator builds of my iPhone app built using MonoTouch. The resx file entry in the csproj file looks like: <ItemGroup> <EmbeddedResource Include="MapMenu\Resources\MapMenu.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>MapMenu.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> The .resx file itself has an entry like this: <data name="Main_Menu" type="System.Resources.ResXFileRef, System.Windows.Forms"> <value>Main Menu.mm;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value> </data> and the generated MapMenu.Designer.cs file has this: internal static string Main_Menu { get { return ResourceManager.GetString("Main_Menu", resourceCulture); } } As mentioned above, calling the Main_Menu accessor works fine on the simulator. On the device, however, it produces: <Notice>: Unhandled Exception: System.MissingMethodException: No constructor found for System.Resources.RuntimeResourceSet::.ctor(System.IO.UnmanagedMemoryStream) <Notice>: at System.Activator.CreateInstance (System.Type type, BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[] args, System.Globalization.CultureInfo culture, System.Object[] activationAttributes) [0x00000] in <filename unknown>:0 <Notice>: at System.Activator.CreateInstance (System.Type type, System.Object[] args, System.Object[] activationAttributes) [0x00000] in <filename unknown>:0 <Notice>: at System.Activator.CreateInstance (System.Type type, System.Object[] args) [0x00000] in <filename unknown>:0 <Notice>: at System.Resources.ResourceManager.InternalGetResourceSet (System.Globalization.CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) [0x00000] in <filename unknown>:0 <Notice>: at System.Resources.ResourceManager.GetString (System.String name, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0 <Notice>: at MapMenu.Resources.MapMenu.get_Main_Menu () [0x00000] in <filename unknown>:0 Did a few sanity checks, and am wondering at this point if this really is missing functionality in Monotouch. Thanks,

    Read the article

  • Generating %pc relative address of constant data

    - by Hudson
    Is there a way to have gcc generate %pc relative addresses of constants? Even when the string appears in the text segment, arm-elf-gcc will generate a constant pointer to the data, load the address of the pointer via a %pc relative address and then dereference it. For a variety of reasons, I need to skip the middle step. As an example, this simple function: const char * filename(void) { static const char _filename[] __attribute__((section(".text"))) = "logfile"; return _filename; } generates (when compiled with arm-elf-gcc-4.3.2 -nostdlib -c -O3 -W -Wall logfile.c): 00000000 <filename>: 0: e59f0000 ldr r0, [pc, #0] ; 8 <filename+0x8> 4: e12fff1e bx lr 8: 0000000c .word 0x0000000c 0000000c <_filename.1175>: c: 66676f6c .word 0x66676f6c 10: 00656c69 .word 0x00656c69 I would have expected it to generate something more like: filename: add r0, pc, #0 bx lr _filename.1175: .ascii "logfile\000" The code in question needs to be partially position independent since it will be relocated in memory at load time, but also integrate with code that was not compiled -fPIC, so there is no global offset table. My current work around is to call a non-inline function (which will be done via a %pc relative address) to find the offset from the compiled location in a technique similar to how -fPIC code works: static intptr_t __attribute__((noinline)) find_offset( void ) { uintptr_t pc; asm __volatile__ ( "mov %0, %%pc" : "=&r"(pc) ); return pc - 8 - (uintptr_t) find_offset; } But this technique requires that all data references be fixed up manually, so the filename() function in the above example would become: const char * filename(void) { static const char _filename[] __attribute__((section(".text"))) = "logfile"; return _filename + find_offset(); }

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >