Search Results

Search found 474 results on 19 pages for 'filepath'.

Page 9/19 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • alternatives to eval for running remote code.

    - by Raynos
    Are there any alternatives to using eval to immediatly run remote & trusted javascript code. function load(filePath) { var o = $.ajax({ url: filePath, dataType: 'html', async: false }); eval(o.responseText); } load("somePath"); // run a function that relies on the code from o.responseText being loaded doSomethingWithCode(); I'm aware that synchronous loading of javascript is adviced againts. But if there is no choice are there any cross browser alternatives for the use of eval above. [Edit] To clarify in more detail the code being loaded is a self executing function. Which needs to execute before doSomethingWidthCode. It's also being loaded from the server on the same domain hence its trusted.

    Read the article

  • Problem When Compressing File using vb.net

    - by Amr Elnashar
    I have File Like "Sample.bak" and when I compress it to be "Sample.zip" I lose the file extension inside the zip file I meann when I open the compressed file I find "Sample" without any extension. I use this code : Dim name As String = Path.GetFileName(filePath).Replace(".Bak", "") Dim source() As Byte = System.IO.File.ReadAllBytes(filePath) Dim compressed() As Byte = ConvertToByteArray(source) System.IO.File.WriteAllBytes(destination & name & ".Bak" & ".zip", compressed) Or using this code : Public Sub cmdCompressFile(ByVal FileName As String) 'Stream object that reads file contents Dim streamObj As Stream = New StreamReader(FileName).BaseStream 'Allocate space in buffer according to the length of the file read Dim buffer(streamObj.Length) As Byte 'Fill buffer streamObj.Read(buffer, 0, buffer.Length) streamObj.Close() 'File Stream object used to change the extension of a file Dim compFile As System.IO.FileStream = File.Create(Path.ChangeExtension(FileName, "zip")) 'GZip object that compress the file Dim zipStreamObj As New GZipStream(compFile, CompressionMode.Compress) 'Write to the Stream object from the buffer zipStreamObj.Write(buffer, 0, buffer.Length) zipStreamObj.Close() End Sub please I need to compress the file without loosing file extension inside compressed file. thanks,

    Read the article

  • Hold the command prompt until user close it from close button.

    - by Kasun
    Hi, I going to get the command prompt from my C# application to compile some C++ files. Code is like this. private void button1_Click(object sender, EventArgs e) { string filePath = @"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe"; System.Diagnostics.Process.Start(filePath); } But After i click the button it suddenly comes and disappear. Even its opening two command prompts. I need to Hold it and only one command prompt should appear. Can some one provide me the necessary codes. Thank you.

    Read the article

  • how to write a text file after the previous line in c#??

    - by riad
    Dear all, My below code create a txt file and write something to that file.but i need to write new line after the previous lines when i run the script several times. code: string filePath = "D:\\DOT_NET\\C#\\abc.txt"; FileInfo t = new FileInfo(filePath); StreamWriter Tex = t.CreateText(); Tex.WriteLine("Hi freinds"); Tex.WriteLine("csharpfriends is the new url for c-sharp"); Tex.Write(Tex.NewLine); Tex.Close(); current output on the abc.txt file: Hi friends csharpfriends is the new url for c-sharp but i need the output if i run the script several times. Hi friends csharpfriends is the new url for c-sharp Hi friends csharpfriends is the new url for c-sharp Hi friends csharpfriends is the new url for c-sharp How can i do that? Pls help thanks Riad

    Read the article

  • explain this macro

    - by deostroll
    #define __T(x) L ## x Found in code from one of the MFC source header file. It is mostly used for converting strings to ........ (I don't know what). If I am correct it converts strings to LPCTSTR...don't know what that type is either... I can't seem to convert char* into LPCTSTR. While MFC file handling, the following code will always return error while trying to open the file... char* filepath = "C:\\Program Files\\Microsoft Office\\Office12\\BITMAPS\\STYLES\\GLOBE.WMF"; if( !file.Open((LPCTSTR)filepath , CFile::modeRead, &fexp) ) { fexp.ReportError(); return 1; } But instead if I wrote it this way, it doesn't give error: if( !file.Open( _T("C:\\Program Files\\Microsoft Office\\Office12\\BITMAPS\\STYLES\\GLOBE.WMF") , CFile::modeRead, &fexp) ) { fexp.ReportError(); return 1; } I am looking at passing a variable as the first argument to the CFile::Open() method.

    Read the article

  • dealing with IO vs pure code in haskell

    - by Drakosha
    I'm writing a shell script (my 1st non-example in haskell) which is supposed to list a directory, get every file size, do some string manipulation (pure code) and then rename some files. I'm not sure what i'm doing wrong, so 2 questions: How should i arrange the code in such program? I have a specific issue, i get the following error, what am i doing wrong? error: Couldn't match expected type [FilePath]' against inferred typeIO [FilePath]' In the second argument of mapM', namelyfileNames' In a stmt of a 'do' expression: files <- (mapM getFileNameAndSize fileNames) In the expression: do { fileNames <- getDirectoryContents; files <- (mapM getFileNameAndSize fileNames); sortBy cmpFilesBySize files } code: getFileNameAndSize fname = do (fname, (withFile fname ReadMode hFileSize)) getFilesWithSizes = do fileNames <- getDirectoryContents files <- (mapM getFileNameAndSize fileNames) sortBy cmpFilesBySize files

    Read the article

  • Within SSIS - Is it possible to deploy one package multiple times in the same instance and set diffe

    - by Matt
    In my environment my Dev and QA Database Instances are on the same server. I would like to deploy the same package (or different versions of the package) into SSIS and set the filter to select different rows in the Config table. Is this possible? This is SQL 2005. For the sake of this question lets say I have one variable, which is a directory path. I would like to have these variables in the table twice (with different Filters applied (Dev and QA) as below (simplified) . . . Filter / Variable Value / Variable Name Dev / c:\data\dev / FilePath QA / c:\data\qa / FilePath Do I need to apply a change within the settings of the package in SSIS or is it changed on the job step within Agent? Any help would be appreciated.

    Read the article

  • Updating a SharePoint master page via a solution (WSP)

    - by Kelly Jones
    In my last blog post, I wrote how to deploy a SharePoint theme using Features and a solution package.  As promised in that post, here is how to update an already deployed master page. There are several ways to update a master page in SharePoint.  You could upload a new version to the master page gallery, or you could upload a new master page to the gallery, and then set the site to use this new page.  Manually uploading your master page to the master page gallery might be the best option, depending on your environment.  For my client, I did these steps in code, which is what they preferred. (Image courtesy of: http://www.joiningdots.net/blog/2007/08/sharepoint-and-quick-launch.html ) Before you decide which method you need to use, take a look at your existing pages.  Are they using the SharePoint dynamic token or the static token for the master page reference?  The wha, huh? SO, there are four ways to tell an .aspx page hosted in SharePoint which master page it should use: “~masterurl/default.master” – tells the page to use the default.master property of the site “~masterurl/custom.master” – tells the page to use the custom.master property of the site “~site/default.master” – tells the page to use the file named “default.master” in the site’s master page gallery “~sitecollection/default.master” – tells the page to use the file named “default.master” in the site collection’s master page gallery For more information about these tokens, take a look at this article on MSDN. Once you determine which token your existing pages are pointed to, then you know which file you need to update.  So, if the ~masterurl tokens are used, then you upload a new master page, either replacing the existing one or adding another one to the gallery.  If you’ve uploaded a new file with a new name, you’ll just need to set it as the master page either through the UI (MOSS only) or through code (MOSS or WSS Feature receiver code – or using SharePoint Designer). If the ~site or ~sitecollection tokens were used, then you’re limited to either replacing the existing master page, or editing all of your existing pages to point to another master page.  In most cases, it probably makes sense to just replace the master page. For my project, I’m working with WSS and the existing pages are set to the ~sitecollection token.  Based on this, I decided to just upload a new version of the existing master page (and not modify the dozens of existing pages). Also, since my client prefers Features and solutions, I created a master page Feature and a corresponding Feature Receiver.  For information on creating the elements and feature files, check out this post: http://sharepointmagazine.net/technical/development/deploying-the-master-page . This works fine, unless you are overwriting an existing master page, which was my case.  You’ll run into errors because the master page file needs to be checked out, replaced, and then checked in.  I wrote code in my Feature Activated event handler to accomplish these steps. Here are the steps necessary in code: Get the file name from the elements file of the Feature Check out the file from the master page gallery Upload the file to the master page gallery Check in the file to the master page gallery Here’s the code in my Feature Receiver: 1: public override void FeatureActivated(SPFeatureReceiverProperties properties) 2: { 3: try 4: { 5:   6: SPElementDefinitionCollection col = properties.Definition.GetElementDefinitions(System.Globalization.CultureInfo.CurrentCulture); 7:   8: using (SPWeb curweb = GetCurWeb(properties)) 9: { 10: foreach (SPElementDefinition ele in col) 11: { 12: if (string.Compare(ele.ElementType, "Module", true) == 0) 13: { 14: // <Module Name="DefaultMasterPage" List="116" Url="_catalogs/masterpage" RootWebOnly="FALSE"> 15: // <File Url="myMaster.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" 16: // Path="MasterPages/myMaster.master" /> 17: // </Module> 18: string Url = ele.XmlDefinition.Attributes["Url"].Value; 19: foreach (System.Xml.XmlNode file in ele.XmlDefinition.ChildNodes) 20: { 21: string Url2 = file.Attributes["Url"].Value; 22: string Path = file.Attributes["Path"].Value; 23: string fileType = file.Attributes["Type"].Value; 24:   25: if (string.Compare(fileType, "GhostableInLibrary", true) == 0) 26: { 27: //Check out file in document library 28: SPFile existingFile = curweb.GetFile(Url + "/" + Url2); 29:   30: if (existingFile != null) 31: { 32: if (existingFile.CheckOutStatus != SPFile.SPCheckOutStatus.None) 33: { 34: throw new Exception("The master page file is already checked out. Please make sure the master page file is checked in, before activating this feature."); 35: } 36: else 37: { 38: existingFile.CheckOut(); 39: existingFile.Update(); 40: } 41: } 42:   43: //Upload file to document library 44: string filePath = System.IO.Path.Combine(properties.Definition.RootDirectory, Path); 45: string fileName = System.IO.Path.GetFileName(filePath); 46: char slash = Convert.ToChar("/"); 47: string[] folders = existingFile.ParentFolder.Url.Split(slash); 48:   49: if (folders.Length > 2) 50: { 51: Logger.logMessage("More than two folders were detected in the library path for the master page. Only two are supported.", 52: Logger.LogEntryType.Information); //custom logging component 53: } 54:   55: SPFolder myLibrary = curweb.Folders[folders[0]].SubFolders[folders[1]]; 56:   57: FileStream fs = File.OpenRead(filePath); 58:   59: SPFile newFile = myLibrary.Files.Add(fileName, fs, true); 60:   61: myLibrary.Update(); 62: newFile.CheckIn("Updated by Feature", SPCheckinType.MajorCheckIn); 63: newFile.Update(); 64: } 65: } 66: } 67: } 68: } 69: } 70: catch (Exception ex) 71: { 72: string msg = "Error occurred during feature activation"; 73: Logger.logException(ex, msg, ""); 74: } 75:   76: } 77:   78: /// <summary> 79: /// Using a Feature's properties, get a reference to the Current Web 80: /// </summary> 81: /// <param name="properties"></param> 82: public SPWeb GetCurWeb(SPFeatureReceiverProperties properties) 83: { 84: SPWeb curweb; 85:   86: //Check if the parent of the web is a site or a web 87: if (properties != null && properties.Feature.Parent.GetType().ToString() == "Microsoft.SharePoint.SPWeb") 88: { 89:   90: //Get web from parent 91: curweb = (SPWeb)properties.Feature.Parent; 92: 93: } 94: else 95: { 96: //Get web from Site 97: using (SPSite cursite = (SPSite)properties.Feature.Parent) 98: { 99: curweb = (SPWeb)cursite.OpenWeb(); 100: } 101: } 102:   103: return curweb; 104: } This did the trick.  It allowed me to update my existing master page, through an easily repeatable process (which is great when you are working with more than one environment and what to do things like TEST it!).  I did run into what I would classify as a strange issue with one of my subsites, but that’s the topic for another blog post.

    Read the article

  • Unauthorized response from Server with API upload

    - by Ethan Shafer
    I'm writing a library in C# to help me develop a Windows application. The library uses the Ubuntu One API. I am able to authenticate and can even make requests to get the Quota (access to Account Admin API) and Volumes (so I know I have access to the Files API at least) Here's what I have as my Upload code: public static void UploadFile(string filename, string filepath) { FileStream file = File.OpenRead(filepath); byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); RestClient client = UbuntuOneClients.FilesClient(); RestRequest request = UbuntuOneRequests.BaseRequest(Method.PUT); request.Resource = "/content/~/Ubuntu One/" + filename; request.AddHeader("Content-Length", bytes.Length.ToString()); request.AddParameter("body", bytes, ParameterType.RequestBody); client.ExecuteAsync(request, webResponse => UploadComplete(webResponse)); } Every time I send the request I get an "Unauthorized" response from the server. For now the "/content/~/Ubuntu One/" is hardcoded, but I checked and it is the location of my root volume. Is there anything that I'm missing? UbuntuOneClients.FilesClient() starts the url with "https://files.one.ubuntu.com" UbuntuOneRequests.BaseRequest(Method.{}) is the same requests that I use to send my Quota and Volumes requests, basically just provides all of the parameters needed to authenticate. EDIT:: Here's the BaseRequest() method: public static RestRequest BaseRequest(Method method) { RestRequest request = new RestRequest(method); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; request.AddParameter("realm", ""); request.AddParameter("oauth_version", "1.0"); request.AddParameter("oauth_nonce", Guid.NewGuid().ToString()); request.AddParameter("oauth_timestamp", DateTime.Now.ToString()); request.AddParameter("oauth_consumer_key", UbuntuOneRefreshInfo.UbuntuOneInfo.ConsumerKey); request.AddParameter("oauth_token", UbuntuOneRefreshInfo.UbuntuOneInfo.Token); request.AddParameter("oauth_signature_method", "PLAINTEXT"); request.AddParameter("oauth_signature", UbuntuOneRefreshInfo.UbuntuOneInfo.Signature); //request.AddParameter("method", method.ToString()); return request; } and the FilesClient() method: public static RestClient FilesClient() { return (new RestClient("https://files.one.ubuntu.com")); }

    Read the article

  • ASP.NET MVC ‘Extendable-hooks’ – ControllerActionInvoker class

    - by nmarun
    There’s a class ControllerActionInvoker in ASP.NET MVC. This can be used as one of an hook-points to allow customization of your application. Watching Brad Wilsons’ Advanced MP3 from MVC Conf inspired me to write about this class. What MSDN says: “Represents a class that is responsible for invoking the action methods of a controller.” Well if MSDN says it, I think I can instill a fair amount of confidence into what the class does. But just to get to the details, I also looked into the source code for MVC. Seems like the base class Controller is where an IActionInvoker is initialized: 1: protected virtual IActionInvoker CreateActionInvoker() { 2: return new ControllerActionInvoker(); 3: } In the ControllerActionInvoker (the O-O-B behavior), there are different ‘versions’ of InvokeActionMethod() method that actually call the action method in question and return an instance of type ActionResult. 1: protected virtual ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) { 2: object returnValue = actionDescriptor.Execute(controllerContext, parameters); 3: ActionResult result = CreateActionResult(controllerContext, actionDescriptor, returnValue); 4: return result; 5: } I guess that’s enough on the ‘behind-the-screens’ of this class. Let’s see how we can use this class to hook-up extensions. Say I have a requirement that the user should be able to get different renderings of the same output, like html, xml, json, csv and so on. The user will type-in the output format in the url and should the get result accordingly. For example: http://site.com/RenderAs/ – renders the default way (the razor view) http://site.com/RenderAs/xml http://site.com/RenderAs/csv … and so on where RenderAs is my controller. There are many ways of doing this and I’m using a custom ControllerActionInvoker class (even though this might not be the best way to accomplish this). For this, my one and only route in the Global.asax.cs is: 1: routes.MapRoute("RenderAsRoute", "RenderAs/{outputType}", 2: new {controller = "RenderAs", action = "Index", outputType = ""}); Here the controller name is ‘RenderAsController’ and the action that’ll get called (always) is the Index action. The outputType parameter will map to the type of output requested by the user (xml, csv…). I intend to display a list of food items for this example. 1: public class Item 2: { 3: public int Id { get; set; } 4: public string Name { get; set; } 5: public Cuisine Cuisine { get; set; } 6: } 7:  8: public class Cuisine 9: { 10: public int CuisineId { get; set; } 11: public string Name { get; set; } 12: } Coming to my ‘RenderAsController’ class. I generate an IList<Item> to represent my model. 1: private static IList<Item> GetItems() 2: { 3: Cuisine cuisine = new Cuisine { CuisineId = 1, Name = "Italian" }; 4: Item item = new Item { Id = 1, Name = "Lasagna", Cuisine = cuisine }; 5: IList<Item> items = new List<Item> { item }; 6: item = new Item {Id = 2, Name = "Pasta", Cuisine = cuisine}; 7: items.Add(item); 8: //... 9: return items; 10: } My action method looks like 1: public IList<Item> Index(string outputType) 2: { 3: return GetItems(); 4: } There are two things that stand out in this action method. The first and the most obvious one being that the return type is not of type ActionResult (or one of its derivatives). Instead I’m passing the type of the model itself (IList<Item> in this case). We’ll convert this to some type of an ActionResult in our custom controller action invoker class later. The second thing (a little subtle) is that I’m not doing anything with the outputType value that is passed on to this action method. This value will be in the RouteData dictionary and we’ll use this in our custom invoker class as well. It’s time to hook up our invoker class. First, I’ll override the Initialize() method of my RenderAsController class. 1: protected override void Initialize(RequestContext requestContext) 2: { 3: base.Initialize(requestContext); 4: string outputType = string.Empty; 5:  6: // read the outputType from the RouteData dictionary 7: if (requestContext.RouteData.Values["outputType"] != null) 8: { 9: outputType = requestContext.RouteData.Values["outputType"].ToString(); 10: } 11:  12: // my custom invoker class 13: ActionInvoker = new ContentRendererActionInvoker(outputType); 14: } Coming to the main part of the discussion – the ContentRendererActionInvoker class: 1: public class ContentRendererActionInvoker : ControllerActionInvoker 2: { 3: private readonly string _outputType; 4:  5: public ContentRendererActionInvoker(string outputType) 6: { 7: _outputType = outputType.ToLower(); 8: } 9: //... 10: } So the outputType value that was read from the RouteData, which was passed in from the url, is being set here in  a private field. Moving to the crux of this article, I now override the CreateActionResult method. 1: protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) 2: { 3: if (actionReturnValue == null) 4: return new EmptyResult(); 5:  6: ActionResult result = actionReturnValue as ActionResult; 7: if (result != null) 8: return result; 9:  10: // This is where the magic happens 11: // Depending on the value in the _outputType field, 12: // return an appropriate ActionResult 13: switch (_outputType) 14: { 15: case "json": 16: { 17: JavaScriptSerializer serializer = new JavaScriptSerializer(); 18: string json = serializer.Serialize(actionReturnValue); 19: return new ContentResult { Content = json, ContentType = "application/json" }; 20: } 21: case "xml": 22: { 23: XmlSerializer serializer = new XmlSerializer(actionReturnValue.GetType()); 24: using (StringWriter writer = new StringWriter()) 25: { 26: serializer.Serialize(writer, actionReturnValue); 27: return new ContentResult { Content = writer.ToString(), ContentType = "text/xml" }; 28: } 29: } 30: case "csv": 31: controllerContext.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=items.csv"); 32: return new ContentResult 33: { 34: Content = ToCsv(actionReturnValue as IList<Item>), 35: ContentType = "application/ms-excel" 36: }; 37: case "pdf": 38: string filePath = controllerContext.HttpContext.Server.MapPath("~/items.pdf"); 39: controllerContext.HttpContext.Response.AddHeader("content-disposition", 40: "attachment; filename=items.pdf"); 41: ToPdf(actionReturnValue as IList<Item>, filePath); 42: return new FileContentResult(StreamFile(filePath), "application/pdf"); 43:  44: default: 45: controllerContext.Controller.ViewData.Model = actionReturnValue; 46: return new ViewResult 47: { 48: TempData = controllerContext.Controller.TempData, 49: ViewData = controllerContext.Controller.ViewData 50: }; 51: } 52: } A big method there! The hook I was talking about kinda above actually is here. This is where different kinds / formats of output get returned based on the output type requested in the url. When the _outputType is not set (string.Empty as set in the Global.asax.cs file), the razor view gets rendered (lines 45-50). This is the default behavior in most MVC applications where-in a view (webform/razor) gets rendered on the browser. As you see here, this gets returned as a ViewResult. But then, for an outputType of json/xml/csv, a ContentResult gets returned, while for pdf, a FileContentResult is returned. Here are how the different kinds of output look like: This is how we can leverage this feature of ASP.NET MVC to developer a better application. I’ve used the iTextSharp library to convert to a pdf format. Mike gives quite a bit of detail regarding this library here. You can download the sample code here. (You’ll get an option to download once you open the link). Verdict: Hot chocolate: $3; Reebok shoes: $50; Your first car: $3000; Being able to extend a web application: Priceless.

    Read the article

  • Uploading and Importing CSV file to SQL Server in ASP.NET WebForms

    - by Vincent Maverick Durano
    Few weeks ago I was working with a small internal project  that involves importing CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project. In this post I will demonstrate how to upload and import CSV file to SQL Server database. As some may have already know, importing CSV file to SQL Server is easy and simple but difficulties arise when the CSV file contains, many columns with different data types. Basically, the provider cannot differentiate data types between the columns or the rows, blindly it will consider them as a data type based on first few rows and leave all the data which does not match the data type. To overcome this problem, I used schema.ini file to define the data type of the CSV file and allow the provider to read that and recognize the exact data types of each column. Now what is schema.ini? Taken from the documentation: The Schema.ini is a information file, used to define the data structure and format of each column that contains data in the CSV file. If schema.ini file exists in the directory, Microsoft.Jet.OLEDB provider automatically reads it and recognizes the data type information of each column in the CSV file. Thus, the provider intelligently avoids the misinterpretation of data types before inserting the data into the database. For more information see: http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx Points to remember before creating schema.ini:   1. The schema information file, must always named as 'schema.ini'.   2. The schema.ini file must be kept in the same directory where the CSV file exists.   3. The schema.ini file must be created before reading the CSV file.   4. The first line of the schema.ini, must the name of the CSV file, followed by the properties of the CSV file, and then the properties of the each column in the CSV file. Here's an example of how the schema looked like: [Employee.csv] ColNameHeader=False Format=CSVDelimited DateTimeFormat=dd-MMM-yyyy Col1=EmployeeID Long Col2=EmployeeFirstName Text Width 100 Col3=EmployeeLastName Text Width 50 Col4=EmployeeEmailAddress Text Width 50 To get started lets's go a head and create a simple blank database. Just for the purpose of this demo I created a database called TestDB. After creating the database then lets go a head and fire up Visual Studio and then create a new WebApplication project. Under the root application create a folder called UploadedCSVFiles and then place the schema.ini on that folder. The uploaded CSV files will be stored in this folder after the user imports the file. Now add a WebForm in the project and set up the HTML mark up and add one (1) FileUpload control one(1)Button and three (3) Label controls. After that we can now proceed with the codes for uploading and importing the CSV file to SQL Server database. Here are the full code blocks below: 1: using System; 2: using System.Data; 3: using System.Data.SqlClient; 4: using System.Data.OleDb; 5: using System.IO; 6: using System.Text; 7:   8: namespace WebApplication1 9: { 10: public partial class CSVToSQLImporting : System.Web.UI.Page 11: { 12: private string GetConnectionString() 13: { 14: return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; 15: } 16: private void CreateDatabaseTable(DataTable dt, string tableName) 17: { 18:   19: string sqlQuery = string.Empty; 20: string sqlDBType = string.Empty; 21: string dataType = string.Empty; 22: int maxLength = 0; 23: StringBuilder sb = new StringBuilder(); 24:   25: sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName)); 26:   27: for (int i = 0; i < dt.Columns.Count; i++) 28: { 29: dataType = dt.Columns[i].DataType.ToString(); 30: if (dataType == "System.Int32") 31: { 32: sqlDBType = "INT"; 33: } 34: else if (dataType == "System.String") 35: { 36: sqlDBType = "NVARCHAR"; 37: maxLength = dt.Columns[i].MaxLength; 38: } 39:   40: if (maxLength > 0) 41: { 42: sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength)); 43: } 44: else 45: { 46: sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType)); 47: } 48: } 49:   50: sqlQuery = sb.ToString(); 51: sqlQuery = sqlQuery.Trim().TrimEnd(','); 52: sqlQuery = sqlQuery + " )"; 53:   54: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 55: { 56: sqlConn.Open(); 57: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 58: sqlCmd.ExecuteNonQuery(); 59: sqlConn.Close(); 60: } 61:   62: } 63: private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter) 64: { 65: string sqlQuery = string.Empty; 66: StringBuilder sb = new StringBuilder(); 67:   68: sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName)); 69: sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath)); 70: sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter)); 71:   72: sqlQuery = sb.ToString(); 73:   74: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 75: { 76: sqlConn.Open(); 77: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 78: sqlCmd.ExecuteNonQuery(); 79: sqlConn.Close(); 80: } 81: } 82: protected void Page_Load(object sender, EventArgs e) 83: { 84:   85: } 86: protected void BTNImport_Click(object sender, EventArgs e) 87: { 88: if (FileUpload1.HasFile) 89: { 90: FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName); 91: if (fileInfo.Name.Contains(".csv")) 92: { 93:   94: string fileName = fileInfo.Name.Replace(".csv", "").ToString(); 95: string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name; 96:   97: //Save the CSV file in the Server inside 'MyCSVFolder' 98: FileUpload1.SaveAs(csvFilePath); 99:   100: //Fetch the location of CSV file 101: string filePath = Server.MapPath("UploadedCSVFiles") + "\\"; 102: string strSql = "SELECT * FROM [" + fileInfo.Name + "]"; 103: string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'"; 104:   105: // load the data from CSV to DataTable 106:   107: OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString); 108: DataTable dtCSV = new DataTable(); 109: DataTable dtSchema = new DataTable(); 110:   111: adapter.FillSchema(dtCSV, SchemaType.Mapped); 112: adapter.Fill(dtCSV); 113:   114: if (dtCSV.Rows.Count > 0) 115: { 116: CreateDatabaseTable(dtCSV, fileName); 117: Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName); 118:   119: string fileFullPath = filePath + fileInfo.Name; 120: LoadDataToDatabase(fileName, fileFullPath, ","); 121:   122: Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName); 123: } 124: else 125: { 126: LBLError.Text = "File is empty."; 127: } 128: } 129: else 130: { 131: LBLError.Text = "Unable to recognize file."; 132: } 133:   134: } 135: } 136: } 137: } The code above consists of three (3) private methods which are the GetConnectionString(), CreateDatabaseTable() and LoadDataToDatabase(). The GetConnectionString() is a method that returns a string. This method basically gets the connection string that is configured in the web.config file. The CreateDatabaseTable() is method that accepts two (2) parameters which are the DataTable and the filename. As the method name already suggested, this method automatically create a Table to the database based on the source DataTable and the filename of the CSV file. The LoadDataToDatabase() is a method that accepts three (3) parameters which are the tableName, fileFullPath and delimeter value. This method is where the actual saving or importing of data from CSV to SQL server happend. The codes at BTNImport_Click event handles the uploading of CSV file to the specified location and at the same time this is where the CreateDatabaseTable() and LoadDataToDatabase() are being called. If you notice I also added some basic trappings and validations within that event. Now to test the importing utility then let's create a simple data in a CSV format. Just for the simplicity of this demo let's create a CSV file and name it as "Employee" and add some data on it. Here's an example below: 1,VMS,Durano,[email protected] 2,Jennifer,Cortes,[email protected] 3,Xhaiden,Durano,[email protected] 4,Angel,Santos,[email protected] 5,Kier,Binks,[email protected] 6,Erika,Bird,[email protected] 7,Vianne,Durano,[email protected] 8,Lilibeth,Tree,[email protected] 9,Bon,Bolger,[email protected] 10,Brian,Jones,[email protected] Now save the newly created CSV file in some location in your hard drive. Okay let's run the application and browse the CSV file that we have just created. Take a look at the sample screen shots below: After browsing the CSV file. After clicking the Import Button Now if we look at the database that we have created earlier you'll notice that the Employee table is created with the imported data on it. See below screen shot.   That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,CSV,SQL,C#,ADO.NET

    Read the article

  • exporting bind and keyframe bone poses from blender to use in OpenGL

    - by SaldaVonSchwartz
    I'm having a hard time trying to understand how exactly Blender's concept of bone transforms maps to the usual math of skinning (which I'm implementing in an OpenGL-based engine of sorts). Or I'm missing out something in the math.. It's gonna be long, but here's as much background as I can think of. First, a few notes and assumptions: I'm using column-major order and multiply from right to left. So for instance, vertex v transformed by matrix A and then further transformed by matrix B would be: v' = BAv. This also means whenever I export a matrix from blender through python, I export it (in text format) in 4 lines, each representing a column. This is so I can then I can read them back into my engine like this: if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[0], &skeleton.joints[currentJointIndex].inverseBindTransform.m[1], &skeleton.joints[currentJointIndex].inverseBindTransform.m[2], &skeleton.joints[currentJointIndex].inverseBindTransform.m[3])) { if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[4], &skeleton.joints[currentJointIndex].inverseBindTransform.m[5], &skeleton.joints[currentJointIndex].inverseBindTransform.m[6], &skeleton.joints[currentJointIndex].inverseBindTransform.m[7])) { if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[8], &skeleton.joints[currentJointIndex].inverseBindTransform.m[9], &skeleton.joints[currentJointIndex].inverseBindTransform.m[10], &skeleton.joints[currentJointIndex].inverseBindTransform.m[11])) { if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[12], &skeleton.joints[currentJointIndex].inverseBindTransform.m[13], &skeleton.joints[currentJointIndex].inverseBindTransform.m[14], &skeleton.joints[currentJointIndex].inverseBindTransform.m[15])) { I'm simplifying the code I show because otherwise it would make things unnecessarily harder (in the context of my question) to explain / follow. Please refrain from making remarks related to optimizations. This is not final code. Having said that, if I understand correctly, the basic idea of skinning/animation is: I have a a mesh made up of vertices I have the mesh model-world transform W I have my joints, which are really just transforms from each joint's space to its parent's space. I'll call these transforms Bj meaning matrix which takes from joint j's bind pose to joint j-1's bind pose. For each of these, I actually import their inverse to the engine, Bj^-1. I have keyframes each containing a set of current poses Cj for each joint J. These are initially imported to my engine in TQS format but after (S)LERPING them I compose them into Cj matrices which are equivalent to the Bjs (not the Bj^-1 ones) only that for the current spacial configurations of each joint at that frame. Given the above, the "skeletal animation algorithm is" On each frame: check how much time has elpased and compute the resulting current time in the animation, from 0 meaning frame 0 to 1, meaning the end of the animation. (Oh and I'm looping forever so the time is mod(total duration)) for each joint: 1 -calculate its world inverse bind pose, that is Bj_w^-1 = Bj^-1 Bj-1^-1 ... B0^-1 2 -use the current animation time to LERP the componets of the TQS and come up with an interpolated current pose matrix Cj which should transform from the joints current configuration space to world space. Similar to what I did to get the world version of the inverse bind poses, I come up with the joint's world current pose, Cj_w = C0 C1 ... Cj 3 -now that I have world versions of Bj and Cj, I store this joint's world- skinning matrix K_wj = Cj_w Bj_w^-1. The above is roughly implemented like so: - (void)update:(NSTimeInterval)elapsedTime { static double time = 0; time = fmod((time + elapsedTime),1.); uint16_t LERPKeyframeNumber = 60 * time; uint16_t lkeyframeNumber = 0; uint16_t lkeyframeIndex = 0; uint16_t rkeyframeNumber = 0; uint16_t rkeyframeIndex = 0; for (int i = 0; i < aClip.keyframesCount; i++) { uint16_t keyframeNumber = aClip.keyframes[i].number; if (keyframeNumber <= LERPKeyframeNumber) { lkeyframeIndex = i; lkeyframeNumber = keyframeNumber; } else { rkeyframeIndex = i; rkeyframeNumber = keyframeNumber; break; } } double lTime = lkeyframeNumber / 60.; double rTime = rkeyframeNumber / 60.; double blendFactor = (time - lTime) / (rTime - lTime); GLKMatrix4 bindPosePalette[aSkeleton.jointsCount]; GLKMatrix4 currentPosePalette[aSkeleton.jointsCount]; for (int i = 0; i < aSkeleton.jointsCount; i++) { F3DETQSType& lPose = aClip.keyframes[lkeyframeIndex].skeletonPose.jointPoses[i]; F3DETQSType& rPose = aClip.keyframes[rkeyframeIndex].skeletonPose.jointPoses[i]; GLKVector3 LERPTranslation = GLKVector3Lerp(lPose.t, rPose.t, blendFactor); GLKQuaternion SLERPRotation = GLKQuaternionSlerp(lPose.q, rPose.q, blendFactor); GLKVector3 LERPScaling = GLKVector3Lerp(lPose.s, rPose.s, blendFactor); GLKMatrix4 currentTransform = GLKMatrix4MakeWithQuaternion(SLERPRotation); currentTransform = GLKMatrix4Multiply(currentTransform, GLKMatrix4MakeTranslation(LERPTranslation.x, LERPTranslation.y, LERPTranslation.z)); currentTransform = GLKMatrix4Multiply(currentTransform, GLKMatrix4MakeScale(LERPScaling.x, LERPScaling.y, LERPScaling.z)); if (aSkeleton.joints[i].parentIndex == -1) { bindPosePalette[i] = aSkeleton.joints[i].inverseBindTransform; currentPosePalette[i] = currentTransform; } else { bindPosePalette[i] = GLKMatrix4Multiply(aSkeleton.joints[i].inverseBindTransform, bindPosePalette[aSkeleton.joints[i].parentIndex]); currentPosePalette[i] = GLKMatrix4Multiply(currentPosePalette[aSkeleton.joints[i].parentIndex], currentTransform); } aSkeleton.skinningPalette[i] = GLKMatrix4Multiply(currentPosePalette[i], bindPosePalette[i]); } } At this point, I should have my skinning palette. So on each frame in my vertex shader, I do: uniform mat4 modelMatrix; uniform mat4 projectionMatrix; uniform mat3 normalMatrix; uniform mat4 skinningPalette[6]; attribute vec4 position; attribute vec3 normal; attribute vec2 tCoordinates; attribute vec4 jointsWeights; attribute vec4 jointsIndices; varying highp vec2 tCoordinatesVarying; varying highp float lIntensity; void main() { vec3 eyeNormal = normalize(normalMatrix * normal); vec3 lightPosition = vec3(0., 0., 2.); lIntensity = max(0.0, dot(eyeNormal, normalize(lightPosition))); tCoordinatesVarying = tCoordinates; vec4 skinnedVertexPosition = vec4(0.); for (int i = 0; i < 4; i++) { skinnedVertexPosition += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * position; } gl_Position = projectionMatrix * modelMatrix * skinnedVertexPosition; } The result: The mesh parts that are supposed to animate do animate and follow the expected motion, however, the rotations are messed up in terms of orientations. That is, the mesh is not translated somewhere else or scaled in any way, but the orientations of rotations seem to be off. So a few observations: In the above shader notice I actually did not multiply the vertices by the mesh modelMatrix (the one which would take them to model or world or global space, whichever you prefer, since there is no parent to the mesh itself other than "the world") until after skinning. This is contrary to what I implied in the theory: if my skinning matrix takes vertices from model to joint and back to model space, I'd think the vertices should already be premultiplied by the mesh transform. But if I do so, I just get a black screen. As far as exporting the joints from Blender, my python script exports for each armature bone in bind pose, it's matrix in this way: def DFSJointTraversal(file, skeleton, jointList): for joint in jointList: poseJoint = skeleton.pose.bones[joint.name] jointTransform = poseJoint.matrix.inverted() file.write('Joint ' + joint.name + ' Transform {\n') for col in jointTransform.col: file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(col[0], col[1], col[2], col[3])) DFSJointTraversal(file, skeleton, joint.children) file.write('}\n') And for current / keyframe poses (assuming I'm in the right keyframe): def exportAnimations(filepath): # Only one skeleton per scene objList = [object for object in bpy.context.scene.objects if object.type == 'ARMATURE'] if len(objList) == 0: return elif len(objList) > 1: return #raise exception? dialog box? skeleton = objList[0] jointNames = [bone.name for bone in skeleton.data.bones] for action in bpy.data.actions: # One animation clip per action in Blender, named as the action animationClipFilePath = filepath[0 : filepath.rindex('/') + 1] + action.name + ".aClip" file = open(animationClipFilePath, 'w') file.write('target skeleton: ' + skeleton.name + '\n') file.write('joints count: {:d}'.format(len(jointNames)) + '\n') skeleton.animation_data.action = action keyframeNum = max([len(fcurve.keyframe_points) for fcurve in action.fcurves]) keyframes = [] for fcurve in action.fcurves: for keyframe in fcurve.keyframe_points: keyframes.append(keyframe.co[0]) keyframes = set(keyframes) keyframes = [kf for kf in keyframes] keyframes.sort() file.write('keyframes count: {:d}'.format(len(keyframes)) + '\n') for kfIndex in keyframes: bpy.context.scene.frame_set(kfIndex) file.write('keyframe: {:d}\n'.format(int(kfIndex))) for i in range(0, len(skeleton.data.bones)): file.write('joint: {:d}\n'.format(i)) joint = skeleton.pose.bones[i] jointCurrentPoseTransform = joint.matrix translationV = jointCurrentPoseTransform.to_translation() rotationQ = jointCurrentPoseTransform.to_3x3().to_quaternion() scaleV = jointCurrentPoseTransform.to_scale() file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2])) file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0])) file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2])) file.write('\n') file.close() Which I believe follow the theory explained at the beginning of my question. But then I checked out Blender's directX .x exporter for reference.. and what threw me off was that in the .x script they are exporting bind poses like so (transcribed using the same variable names I used so you can compare): if joint.parent: jointTransform = poseJoint.parent.matrix.inverted() else: jointTransform = Matrix() jointTransform *= poseJoint.matrix and exporting current keyframe poses like this: if joint.parent: jointCurrentPoseTransform = joint.parent.matrix.inverted() else: jointCurrentPoseTransform = Matrix() jointCurrentPoseTransform *= joint.matrix why are they using the parent's transform instead of the joint in question's? isn't the join transform assumed to exist in the context of a parent transform since after all it transforms from this joint's space to its parent's? Why are they concatenating in the same order for both bind poses and keyframe poses? If these two are then supposed to be concatenated with each other to cancel out the change of basis? Anyway, any ideas are appreciated.

    Read the article

  • Calling Grep inside Java gives incorrect results while calling grep in shell gives correct results.

    - by futureelite7
    I've got a problem where calling grep from inside java gives incorrect results, as compared to the results from calling grep on the same file in the shell. My grep command (called both in Java and in bash. I escaped the slash in Java accordingly): /bin/grep -vP --regexp='^[0-9]+\t.*' /usr/local/apache-tomcat-6.0.18/work/Catalina/localhost/saccitic/237482319867147879_1271411421 Java Code: String filepath = "/path/to/file"; String options = "P"; String grepparams = "^[0-9]+\\t.*"; String greppath = "/bin/"; String[] localeArray = new String[] { "LANG=", "LC_COLLATE=C", "LC_CTYPE=UTF-8", "LC_MESSAGES=C", "LC_MONETARY=C", "LC_NUMERIC=C", "LC_TIME=C", "LC_ALL=" }; options = "v"+options; //Assign optional params if (options.contains("P")) { grepparams = "\'"+grepparams+"\'"; //Quote the regex expression if -P flag is used } else { options = "E"+options; //equivalent to calling egrep } proc = sysRuntime.exec(greppath+"/grep -"+options+" --regexp="+grepparams+" "+filepath, localeArray); System.out.println(greppath+"/grep -"+options+" --regexp="+grepparams+" "+filepath); inStream = proc.getInputStream(); The command is supposed to match and discard strings like these: 85295371616 Hi Mr Lee, please be informed that... My input file is this: 85aaa234567 Hi Ms Chan, please be informed that... 85292vx5678 Hi Mrs Ng, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85aaa234567 Hi Ms Chan, please be informed that... 85292vx5678 Hi Mrs Ng, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 8~!95371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 852&^*&1616 Hi Mr Lee, please be informed that... 8529537Ax16 Hi Mr Lee, please be informed that... 85====ppq16 Hi Mr Lee, please be informed that... 85291234783 a3283784428349247233834728482984723333 85219299222 The commands works when I call it from inside bash (Results below): 85aaa234567 Hi Ms Chan, please be informed that... 85292vx5678 Hi Mrs Ng, please be informed that... 85aaa234567 Hi Ms Chan, please be informed that... 85292vx5678 Hi Mrs Ng, please be informed that... 8~!95371616 Hi Mr Lee, please be informed that... 852&^*&1616 Hi Mr Lee, please be informed that... 8529537Ax16 Hi Mr Lee, please be informed that... 85====ppq16 Hi Mr Lee, please be informed that... 85219299222 However, when I call grep again inside java, I get the entire file (Results below): 85aaa234567 Hi Ms Chan, please be informed that... 85292vx5678 Hi Mrs Ng, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85aaa234567 Hi Ms Chan, please be informed that... 85292vx5678 Hi Mrs Ng, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 8~!95371616 Hi Mr Lee, please be informed that... 85295371616 Hi Mr Lee, please be informed that... 852&^*&1616 Hi Mr Lee, please be informed that... 8529537Ax16 Hi Mr Lee, please be informed that... 85====ppq16 Hi Mr Lee, please be informed that... 85291234783 a3283784428349247233834728482984723333 85219299222 What could be the problem that will cause the grep called by Java to return incorrect results? I tried passing local information via the environment string array in runtime.exec, but nothing seems to change. Am I passing in the locale information incorrectly, or is the problem something else entirely?

    Read the article

  • Opening an SQL CE file at runtime with Entity Framework 4

    - by David Veeneman
    I am getting started with Entity Framework 4, and I an creating a demo app as a learning exercise. The app is a simple documentation builder, and it uses a SQL CE store. Each documentation project has its own SQL CE data file, and the user opens one of these files to work on a project. The EDM is very simple. A documentation project is comprised of a list of subjects, each of which has a title, a description, and zero or more notes. So, my entities are Subject, which contains Title and Text properties, and Note, which has Title and Text properties. There is a one-to-many association from Subject to Note. I am trying to figure out how to open an SQL CE data file. A data file must match the schema of the SQL CE database created by EF4's Create Database Wizard, and I will implement a New File use case elsewhere in the app to implement that requirement. Right now, I am just trying to get an existing data file open in the app. I have reproduced my existing 'Open File' code below. I have set it up as a static service class called File Services. The code isn't working quite yet, but there is enough to show what I am trying to do. I am trying to hold the ObjectContext open for entity object updates, disposing it when the file is closed. So, here is my question: Am I on the right track? What do I need to change to make this code work with EF4? Is there an example of how to do this properly? Thanks for your help. My existing code: public static class FileServices { #region Private Fields // Member variables private static EntityConnection m_EntityConnection; private static ObjectContext m_ObjectContext; #endregion #region Service Methods /// <summary> /// Opens an SQL CE database file. /// </summary> /// <param name="filePath">The path to the SQL CE file to open.</param> /// <param name="viewModel">The main window view model.</param> public static void OpenSqlCeFile(string filePath, MainWindowViewModel viewModel) { // Configure an SQL CE connection string var sqlCeConnectionString = string.Format("Data Source={0}", filePath); // Configure an EDM connection string var builder = new EntityConnectionStringBuilder(); builder.Metadata = "res://*/EF4Model.csdl|res://*/EF4Model.ssdl|res://*/EF4Model.msl"; builder.Provider = "System.Data.SqlServerCe"; builder.ProviderConnectionString = sqlCeConnectionString; var entityConnectionString = builder.ToString(); // Connect to the model m_EntityConnection = new EntityConnection(entityConnectionString); m_EntityConnection.Open(); // Create an object context m_ObjectContext = new Model1Container(); // Get all Subject data IQueryable<Subject> subjects = from s in Subjects orderby s.Title select s; // Set view model data property viewModel.Subjects = new ObservableCollection<Subject>(subjects); } /// <summary> /// Closes an SQL CE database file. /// </summary> public static void CloseSqlCeFile() { m_EntityConnection.Close(); m_ObjectContext.Dispose(); } #endregion }

    Read the article

  • How to save data from multiple views of an iPhone app?

    - by DownUnder
    Hi Everyone. I'm making an app where I need to save the text in multiple views in the app when the app quits. I also need to be able to remove all of the data from just one of those views and when the app quits, it's possible not all of those views will have been created yet. After reading this post I thought perhaps it would be good to use a singleton that manages my app data which loads in the data when it is first requested and saved it when the app quits. Then in each view where I need to save data I can just set it on the singleton. I gave it a go but have run into some issues. At first I didn't synthesize the properties (as in the post I was using as a guide) but the compiler told me I needed to make getters and setters, so I did. Now when my applicationWIllTerminate: gets call the app crashes and the console says "Program received signal: “EXC_BAD_ACCESS”. kill quit". Is anyone able to tell me what I'm doing wrong, or suggest a better approach to saving the data? //SavedData.h #import <Foundation/Foundation.h> #define kFileName @"appData.plist" @interface SavedData : NSObject { NSString *information; NSString *name; NSString *email; NSString *phone; NSString *mobile; } @property(assign) NSString *information; @property(assign) NSString *name; @property(assign) NSString *email; @property(assign) NSString *phone; @property(assign) NSString *mobile; + (SavedData *)singleton; + (NSString *)dataFilePath; + (void)applicationWillTerminate:(NSNotification *)notification; @end //SavedData.m #import "SavedData.h" @implementation SavedData @synthesize information; @synthesize name; @synthesize email; @synthesize phone; @synthesize mobile; static SavedData * SavedData_Singleton = nil; + (SavedData *)singleton{ if (nil == SavedData_Singleton){ SavedData_Singleton = [[SavedData_Singleton alloc] init]; NSString *filePath = [self dataFilePath]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ NSMutableArray * array = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; information = [array objectAtIndex:0]; name = [array objectAtIndex:1]; email = [array objectAtIndex:2]; phone = [array objectAtIndex:3]; mobile = [array objectAtIndex:4]; [array release]; } UIApplication *app = [UIApplication sharedApplication]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app]; } return SavedData_Singleton; } + (NSString *)dataFilePath{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *DocumentsDirectory = [paths objectAtIndex:0]; return [DocumentsDirectory stringByAppendingPathComponent:kFileName]; } + (void)applicationWillTerminate:(NSNotification *)notification{ NSLog(@"Application will terminate received"); NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:information]; [array addObject:name]; [array addObject:email]; [array addObject:phone]; [array addObject:mobile]; [array writeToFile:[self dataFilePath] atomically:YES]; [array release]; } @end Then when I want to use it I do myLabel.text = [SavedData singleton].information; And when I change the field [SavedData singleton].information = @"my string"; Any help will be very much appreciated!

    Read the article

  • Reading Excel using ClosedXML

    I have used closedXML api to read the excel. Here is how you do it. Statistically, this performs better than OpenXML. public DataTable ReadDataFromExcelUsingClosedXML()         { string filePath ="@c:/temp/example.xlsx";             var LobjWorkbook = new XLWorkbook(filePath);             var LobjWorksheet = LobjWorkbook.Worksheets.First();             var LobjFullRange = LobjWorksheet.RangeUsed();             var LobjUsedRange = LobjWorksheet.Range(MobjImportMapper.HeaderRowIndex + 1, 1, LobjFullRange.RangeAddress.LastAddress.RowNumber,                                                     LobjFullRange.RangeAddress.LastAddress.ColumnNumber);             var LiNumberOfcolumnsInTheExcel = LobjUsedRange.ColumnCount();             //  for progress bar             int LiAggregateRowCounter = MobjImportMapper.HeaderRowIndex;             int LiTotalNumberOfRows = LobjWorksheet.RowCount() - LiAggregateRowCounter;             int LiPercentage = 0;             foreach (var LobjRow in LobjUsedRange.RowsUsed())             {                 int LiTemp = 0;                 object[] LobjrowData = new object[LiNumberOfcolumnsInTheExcel + 1];                 LobjrowData[LiTemp] = LobjRow.RangeAddress.FirstAddress.RowNumber;                 LiTemp++;                 LobjRow.Cells().ForEach(PobjCell => LobjrowData[LiTemp++] = PobjCell.Value);                 LdtExcelData.Rows.Add(LobjrowData);                 //  for progress bar                 LiPercentage = ((100 * LiAggregateRowCounter / LiTotalNumberOfRows) / 4) * 3;                 if (LiPercentage > 5)                     PobjBackgoundWorker.ReportProgress(LiPercentage);                 LiAggregateRowCounter++;                 // =====================             }             return LdtExcelData;         } span.fullpost {display:none;}

    Read the article

  • Taking a screenshot from within a Silverlight #WP7 application

    - by Laurent Bugnion
    Often times, you want to take a screenshot of an application’s page. There can be multiple reasons. For instance, you can use this to provide an easy feedback method to beta testers. I find this super invaluable when working on integration of design in an app, and the user can take quick screenshots, attach them to an email and send them to me directly from the Windows Phone device. However, the same mechanism can also be used to provide screenshots are a feature of the app, for example if the user wants to save the current status of his application, etc. Caveats Note the following: The code requires an XNA library to save the picture to the media library. To have this, follow the steps: In your application (or class library), add a reference to Microsoft.Xna.Framework. In your code, add a “using” statement to Microsoft.Xna.Framework.Media. In the Properties folder, open WMAppManifest.xml and add the following capability: ID_CAP_MEDIALIB. The method call will fail with an exception if the device is connected to the Zune application on the PC. To avoid this, either disconnect the device when testing, or end the Zune application on the PC. While the method call will not fail on the emulator, there is no way to access the media library, so it is pretty much useless on this platform. This method only prints Silverlight elements to the output image. Other elements (such as a WebBrowser control’s content for instance) will output a black rectangle. The code public static void SaveToMediaLibrary( FrameworkElement element, string title) { try { var bmp = new WriteableBitmap(element, null); var ms = new MemoryStream(); bmp.SaveJpeg( ms, (int)element.ActualWidth, (int)element.ActualHeight, 0, 100); ms.Seek(0, SeekOrigin.Begin); var lib = new MediaLibrary(); var filePath = string.Format(title + ".jpg"); lib.SavePicture(filePath, ms); MessageBox.Show( "Saved in your media library!", "Done", MessageBoxButton.OK); } catch { MessageBox.Show( "There was an error. Please disconnect your phone from the computer before saving.", "Cannot save", MessageBoxButton.OK); } } This method can save any FrameworkElement. Typically I use it to save a whole page, but you can pass any other element to it. On line 7, we create a new WriteableBitmap. This excellent class can render a visual tree into a bitmap. Note that for even more features, you can use the great WriteableBitmapEx class library (which is open source). On lines 9 to 16, we save the WriteableBitmap to a MemoryStream. The only format supported by default is JPEG, however it is possible to convert to other formats with the ImageTools library (also open source). Lines 18 to 20 save the picture to the Windows Phone device’s media library. Using the image To retrieve the image, simply launch the Pictures library on the phone. The image will be in Saved Pictures. From here, you can share the image (by email, for instance), or synchronize it with the PC using the Zune software. Saving to other platforms It is of course possible to save to other platforms than the media library. For example, you can send the image to a web service, or save it to the isolated storage on the device. To do this, instead of using a MemoryStream, you can use any other stream (such as a web request stream, or a file stream) and save to that instead. Hopefully this code will be helpful to you! Happy coding, Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • IOS: How to uplaod a file to specific google drive folder using google drive sdk library

    - by loganathan
    I integrated google drive sdk with my ios app. But i do not know how to upload a file to google drive specific folder. Here the code am using to upload the file. But this one uploading the file to my google drive root folder. Any one share a code to upload a file to google drive specific folder?. My Code: -(void)uploadFileToGoogleDrive:(NSString*)fileName { GTLDriveFile *driveFile = [[[GTLDriveFile alloc]init] autorelease]; driveFile.mimeType = @"application/pdf"; driveFile.originalFilename = @"test.doc"; driveFile.title = @"test.doc"; NSString *filePath = [LocalFilesDetails getUserDocumentFullPathForFileName:fileName isSignedDocument:YES]; GTLUploadParameters *uploadParameters = [GTLUploadParameters uploadParametersWithData:[NSData dataWithContentsOfFile:filePath] MIMEType:@"application/pdf"]; GTLQueryDrive *query = [GTLQueryDrive queryForFilesInsertWithObject:driveFile uploadParameters:uploadParameters]; [self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *updatedFile, NSError *error) { if (error == nil) { NSLog(@"\n\nfile uploaded into google drive\\<my_folder> foler"); } else { NSLog(@"\n\nfile uplod failed google drive\\<my_folder> foler"); } }]; }

    Read the article

  • why AVAudioplayer doesn't stop/pause when viewWillDisappear?

    - by Rahul Vyas
    I am using avaudioplayer in my app. on viewwilldisappear i want to pause/stop the sound and on viewwill appear i want to play sound again.how do i do this? i'm using this code on viewWillAppear:- if(self.TickPlayer) { [self.TickPlayer play]; } if(self.TickPlayer.volume<0) { self.TickPlayer.volume=1.0; } and this on viewWillDisAppear if(self.TickPlayer) { [self.TickPlayer stop]; } here is the method which plays the sound -(void)PlayTickTickSound:(NSString*)SoundFileName { //Get the filename of the sound file: NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],[NSString stringWithFormat:@"/%@",SoundFileName]]; //Get a URL for the sound file NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO]; NSError *error; if(self.TickPlayer==nil) { self.TickPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:&error]; // handle errors here. self.TickPlayer.delegate=self; [self.TickPlayer setNumberOfLoops:-1]; // repeat forever [self.TickPlayer play]; } if(self.TickPlayer) { [self.TickPlayer play]; } } and i'm calling it in method which fires every second using a timer in viewDidLoad- self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES]; -(void) updateCountdown { [self PlayTickTickSound:@"tick.caf"]; } i'm also playing a beep sound using avaudioplayer at a specific condition when alert appears.that works fine but this is not working as expected

    Read the article

  • How to deal with special characters in ASP.NET's HyperLink.NavigateUrl?

    - by DJ Pirtu
    I am currently having troubles figuring out how to handle a filepath to be (dynamicly) passed out to a HyperLink control's NavigateUrl property. Let's say that I'm trying to refer to a file named jäynä.txt at the root of C:. Passing "file:///C:/jäynä.txt" result to a link to file:///C:/jäynä.txt, as does HttpUtility.UrlPathEncode("file:///C:/jäynä.txt"). Replacing the äs with %E4, which gives the string "file:///C:/j%E4yn%E4.txt", does give a working link to file:///C:/jäynä.txt, but I have not been able to find a way to make the replacement without defining it myself. With Replace("ä", "%E4"), for example. Is there a way to automaticly handle the filepath string so that the HyperLink would display it correctly, without manualy listing what characters to replace in the string? Additional Note: There may be a way to work around this by spesifying the character encoding in which the page is rendered, because debugging shows that the HyperLink at least saves the string "file:///C:/jäynä.txt" unchanged, but somehow mangles it around the time of rendering. However, this seems only be the case in rendering of the NavigateUrl because other components as well as HyperLink's Text-property are all quite capable of rendering the character ä unchanged.

    Read the article

  • Problem using AVAudioRecorder.

    - by tek3
    Hi all, I am facing a strange problem with AVAudioRecorder. In my application i need to record audio and play it. I am creating my player as : if(recorder) { if(recorder.recording) [recorder stop]; [recorder release]; recorder = nil; } NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/%@.caf",songTitle]]; NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithFloat: 44100.0],AVSampleRateKey, [NSNumber numberWithInt: kAudioFormatAppleIMA4],AVFormatIDKey, [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityMax],AVEncoderAudioQualityKey,nil]; recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:filePath] settings: recordSettings error: nil]; recorder.delegate = self; if ([recorder prepareToRecord] == YES){ [recorder record]; I am releasing and creating player every time i press record button. But the problem is that ,AVAudiorecorder is taking some time before starting to record , and so if i press record button multiple times continuously ,my application freezes for some time. The same code works fine without any problem when headphones are connected to device...there is no delay in recording, and the app doesn't freeze even if i press record button multiple times. Any help in this regard will be highly appreciated. Thanx in advance.

    Read the article

  • as3crypto PEM.readRSAPublicKey returns null

    - by www.jefferyfernandez.id.au
    I am trying to implement a bit of encryption in my Air application while communication with a PHP backend server. For this purpose I am using as3crypto library and I can't read the public key to make the encryption possible. Here is my action script code: var rsa:RSAKey = PEM.readRSAPublicKey(this.readApplicationFileContents('server.crt')); if ( rsa ) { var encodeSource:ByteArray = Hex.toArray(Hex.fromString("Hello World")); var encodeDestination:ByteArray = new ByteArray; var encodeDestination2:ByteArray = new ByteArray; rsa.encrypt(encodeSource, encodeDestination, encodeSource.length) rsa.decrypt(encodeDestination, encodeDestination2, encodeDestination.length); trace(encodeDestination2.toString()); } private function readApplicationFileContents(filePath:String):String { var fileObject:File = File.applicationDirectory.resolvePath(filePath); var fileStream:FileStream = new FileStream(); fileStream.open(fileObject, FileMode.READ); var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); return(fileContents); } readApplicationFileContents function returns the proper certificate contents as a string. But rsa variable always returns null. It would have been easier if I was able to compile the as3crypto library so I can debug through the source, but I can't get the library to compile and can't find any instructions to do the same. Anyone have a clue what's wrong? PS. Sorry first time poster and I can't seem to get the syntax highlighting right. Must be Chrome is not working well with the editor.

    Read the article

  • Multiple Configuration Sources for Enterprise Library 4.1?

    - by Martijn B
    Hi All, We use the caching and logging application blocks from entlib 4.1. We want to keep the configuration of those two in seperate files. How can we achieve this? It looks like entlib is always using the selectedSource as it configuration. I tried the following: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=9057346a2b2dcfc8" /> </configSections> <enterpriseLibrary.ConfigurationSource selectedSource="messagesCache"> <sources> <add name="messagesCache" filePath="Configuration\\messagesCache.config" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=9057346a2b2dcfc8" /> <add name="logging" filePath="Configuration\\logging.config" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=9057346a2b2dcfc8" /> </sources> </enterpriseLibrary.ConfigurationSource> </configuration> But this doesn't work because the application blocks always use the selectedSource attribute value. Any suggestions woulde be welcome! Gr Martijn

    Read the article

  • Android:Playing bigger size audio wav sound file produces crash

    - by user187532
    Hi Android experts, I am trying to play the bigger size audio wav file(which is 20 mb) using the following code(AudioTrack) on my Android 1.6 HTC device which basically has less memory. But i found device crash as soon as it executes reading, writing and play. But the same code works fine and plays the lesser size audio wav files(10kb, 20 kb files etc) very well. P.S: I should play PCM(.wav) buffer sound, the reason behind why i use AudioTrack here. Though my device has lesser memory, how would i read bigger audio files bytes by bytes and play the sound to avoid crashing due to memory constraints. private void AudioTrackPlayPCM() throws IOException { String filePath = "/sdcard/myWav.wav"; // 8 kb file byte[] byteData = null; File file = null; file = new File(filePath); byteData = new byte[(int) file.length()]; FileInputStream in = null; try { in = new FileInputStream( file ); in.read( byteData ); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int intSize = android.media.AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT); AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, intSize, AudioTrack.MODE_STREAM); at.play(); at.write(byteData, 0, byteData.length); at.stop(); at.release(); } Could someone guide me please to play the AudioTrack code for bigger size wav files?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >