Search Results

Search found 266 results on 11 pages for 'fileinfo'.

Page 5/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • How do I locate a particular word in a text file using .NET

    - by cmrhema
    I am sending mails (in asp.net ,c#), having a template in text file (.txt) like below User Name :<User Name> Address : <Address>. I used to replace the words within the angle brackets in the text file using the below code StreamReader sr; sr = File.OpenText(HttpContext.Current.Server.MapPath(txt)); copy = sr.ReadToEnd(); sr.Close(); //close the reader copy = copy.Replace(word.ToUpper(),"#" + word.ToUpper()); //remove the word specified UC //save new copy into existing text file FileInfo newText = new FileInfo(HttpContext.Current.Server.MapPath(txt)); StreamWriter newCopy = newText.CreateText(); newCopy.WriteLine(copy); newCopy.Write(newCopy.NewLine); newCopy.Close(); Now I have a new problem, the user will be adding new words within an angle, say for eg, they will be adding <Salary>. In that case i have to read out and find the word <Salary>. In other words, I have to find all the words, that are located with the angle brackets (<). How do I do that?

    Read the article

  • Read text file into listbox collections

    - by Arcadian
    Hi, i'm new to C#. I need my program to show different parts of the data contained in a txt file into different listboxs (which are on different tabs of a form) so that the user can see the particular block of data they are interested in. the data contained in the txt file looks like this: G30:39:03:31 JG06 G32:56:36:10 JG04 G31:54:69:52 JG04 G36:32:53:11 JG05 G33:50:05:11 JG06 G39:28:81:21 JG01 G39:22:74:11 JG06 G39:51:44:21 JG03 G39:51:52:22 JG01 G39:51:73:21 JG01 G35:76:24:20 JG06 G35:76:55:11 JG01 G36:31:96:11 JG02 G36:31:96:23 JG02 G36:31:96:41 JG03 though much more of it :) The separate listboxes will contain only the lines who's first integer pair matches that listbox's name. For example, all the lines that start "G32" will be added to the G32 listbox. I think the code would start something like: private void ReadToBox() { FileInfo file = new FileInfo("Jumpgate List.JG"); StreamReader objRead = file.OpenText(); while (!objRead.EndOfStream) but i'm not sure where to start in terms of getting it sorted yet. Any help? There's some rep in it for you :D

    Read the article

  • Error when decoding image C# asp

    - by Wayneio
    I am trying to use MessagingToolkit to decode an image in C#/ASP. I have managed to encode a qr using this package, but when i try to decode, using the code below it comes up with 2 errors (at the bottom of the page) I believe this is because I am not getting the image correctly after uploading, but can someone point out exactly where I have gone wrong. Thanks. protected void CreateCode_OnClick(object sender, EventArgs e) { string path = "C:\\Users\\Wayneio\\Documents\\Visual Studio 2012\\Projects\\BAMSystem\\BAMSystem\\"; if (QRUpload.HasFiles == true) { FileInfo fi = new FileInfo(QRUpload.FileName); string extA = fi.Extension; if (extA == ".jpg" || extA == ".png") { QRCodeDecoder decoder = new QRCodeDecoder(); QRUpload.SaveAs(path + QRUpload.FileName); System.Drawing.Image myImg = System.Drawing.Image.FromFile(path + QRUpload.FileName); decoder.Decode(myImg); } else { error.Text = "You have uploaded a " + extA + " file. Please upload either a PNG or a JPG"; } } else { error.Text = "You have not uploaded an image."; } } Error1: Error 2 Argument 1: cannot convert from 'System.Drawing.Image' to 'MessagingToolkit.QRCode.Codec.Data.QRCodeImage' c:\users\wayneio\documents\visual studio 2012\Projects\BAMSystem\BAMSystem\default.aspx.cs 38 35 BAMSystem Error2: Error 1 The best overloaded method match for 'MessagingToolkit.QRCode.Codec.QRCodeDecoder.Decode(MessagingToolkit.QRCode.Codec.Data.QRCodeImage)' has some invalid arguments c:\users\wayneio\documents\visual studio 2012\Projects\BAMSystem\BAMSystem\default.aspx.cs 38 20 BAMSystem P.S if anyone has documentation on this MessagingToolkit QR package, it would be useful

    Read the article

  • How can I execute a .sql from C#?

    - by J. Pablo Fernández
    For some integration tests I want to connect to the database and run a .sql file that has the schema needed for the tests to actually run, including GO statements. How can I execute the .sql file? (or is this totally the wrong way to go?) I've found a post in the MSDN forum showing this code: using System.Data.SqlClient; using System.IO; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True"; FileInfo file = new FileInfo("C:\\myscript.sql"); string script = file.OpenText().ReadToEnd(); SqlConnection conn = new SqlConnection(sqlConnectionString); Server server = new Server(new ServerConnection(conn)); server.ConnectionContext.ExecuteNonQuery(script); } } } but on the last line I'm getting this error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --- System.TypeInitializationException: The type initializer for '' threw an exception. --- .ModuleLoadException: The C++ module failed to load during appdomain initialization. --- System.DllNotFoundException: Unable to load DLL 'MSVCR80.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E). I was told to go and download that DLL from somewhere, but that sounds very hacky. Is there a cleaner way to? Is there another way to do it? What am I doing wrong? I'm doing this with Visual Studio 2008, SQL Server 2008, .Net 3.5SP1 and C# 3.0.

    Read the article

  • Check if file is locked or catch error for trying to open

    - by Duncan Matheson
    I'm trying to handle the problem where a user can try to open, with an OpenFileDialog, a file that is open by Excel. Using the simple FileInfo.OpenRead(), it chucks an IOException, "The process cannot access the file 'cakes.xls' because it is being used by another process." This would be fine to display to the user except that the user will actually get "Debugging resource strings are unavailable" nonsense. It seems not possible to open a file that is open by another process, since using FileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite) chucks a SecurityException, "File operation not permitted. Access to path 'C:\whatever\cakes.xls' is denied.", for any file. Rather unhelpful. So it's down to either finding some way of checking if the file is locked, or trying to catch the IOException. I don't want to catch all IOExceptions and assume they're all locked file errors, so I need some sort of way of classifying this type of exception as this error... but the "Debugging resource strings" nonsense along with the fact that that message itself is probably localized makes it tricky. I'm partial trust, so I can't use Marshal.GetHRForException. So: Is there any sensible way of either check if a file is locked, or at least determining if this problem occurred without just catching all IOExceptions?

    Read the article

  • How do I locate a particular word in a text file using C#

    - by cmrhema
    Hi, I am sending mails (in asp.net ,c#), having a template in text file (.txt) like below User Name :<User Name> Address : <Address>. I used to replace the words within the angle brackets in the text file using the below code StreamReader sr; sr = File.OpenText(HttpContext.Current.Server.MapPath(txt)); copy = sr.ReadToEnd(); sr.Close(); //close the reader copy = copy.Replace(word.ToUpper(),"#" + word.ToUpper()); //remove the word specified UC //save new copy into existing text file FileInfo newText = new FileInfo(HttpContext.Current.Server.MapPath(txt)); StreamWriter newCopy = newText.CreateText(); newCopy.WriteLine(copy); newCopy.Write(newCopy.NewLine); newCopy.Close(); Now I have a new problem, the user will be adding new words within an angle, say for eg, they will be adding <Salary>. In that case i have to read out and find the word <Salary>. In other words, I have to find all the words, that are located with the angle brackets (<). How do I do that. Kindly do let me know. Thanks.

    Read the article

  • IO operation taking long time for files in remote server

    - by user841311
    I have files of size 150 MB each in a remote server in a different domain in the network. I am accessing them thorugh UNC path. I want to read the file content and perform a basic string search. When I try reading the files line by line, the operation just don't finish and takes long time, more than 30 minutes. However when I copy those files to my local machine, the same code reads and performs the string search in less than 5 seconds. I don't have .NET framework installed in the server so I have to do this from my machine. I want to perform all this through C# code in .NET framework 3.5 so I don't want to explictly ftp all the files to my machine before performing this operation. Sample Code DirectoryInfo dir = new DirectoryInfo(@strFilePath); FileInfo[] fiArray = dir.getFiles("*.txt"); foreach (FileInfo fi in fiArray) { //reading file content from server takes long time but fast in local machine //perform string search } Let me know if my requirement is not clear. Thanks in advance!

    Read the article

  • GetAccessControl error with NTAccount

    - by Adam Witko
    private bool HasRights(FileSystemRights fileSystemRights_, string fileName_, bool isFile_) { bool hasRights = false; WindowsIdentity WinIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); WindowsPrincipal WinPrincipal = new WindowsPrincipal(WinIdentity); AuthorizationRuleCollection arc = null; if (isFile_) { FileInfo fi = new FileInfo(@fileName_); arc = fi.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryInfo di = new DirectoryInfo(@fileName_); arc = di.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); } foreach (FileSystemAccessRule rule in arc) { if (WinPrincipal.IsInRole(rule.IdentityReference.Value)) { if (((int)rule.FileSystemRights & (int)fileSystemRights_) > 0) { if (rule.AccessControlType == AccessControlType.Allow) hasRights = true; else if (rule.AccessControlType == AccessControlType.Deny) { hasRights = false; break; } } } } return hasRights; } The above code block is causing me problems. When the WinPrincipal.IsInRole(rule.IdentityReference.Value) is executed the following exception occurs: "The trust relationship between the primary domain and the trusted domain failed.". I'm very new to using identities, principles and such so I don't know what's the problem. I'm assuming it's with the use of NTAccount? Thanks

    Read the article

  • Why am I getting this error when overriding an inherited method?

    - by Sergio Tapia
    Here's my parent class: public abstract class BaseFile { public string Name { get; set; } public string FileType { get; set; } public long Size { get; set; } public DateTime CreationDate { get; set; } public DateTime ModificationDate { get; set; } public abstract void GetFileInformation(); public abstract void GetThumbnail(); } And here's the class that's inheriting it: public class Picture:BaseFile { public override void GetFileInformation(string filePath) { FileInfo fileInformation = new FileInfo(filePath); if (fileInformation.Exists) { Name = fileInformation.Name; FileType = fileInformation.Extension; Size = fileInformation.Length; CreationDate = fileInformation.CreationTime; ModificationDate = fileInformation.LastWriteTime; } } public override void GetThumbnail() { } } I thought when a method was overridden, I could do what I wanted with it. Any help please? :)

    Read the article

  • Create a new webpage using a WCF service

    - by sweeney
    Hello, I'd like to create WCF operation contract which consumes a string, produces a public webpage and then returns the address of this new page. [ServiceContract(Namespace = "")] public class DatabaseService { [OperationContract] public string BuildPage(string fileName, string html) { //writes html to file //returns public file url } } This doesn't seem like it should be complicated but i cant figure out how to do it. So far what i've tried is this: [OperationContract] public string PrintToFile(string name, string text) { FileInfo f = new FileInfo(name); StreamWriter w = f.AppendText(); w.Write(text); w.Close(); return f.Directory.ToString(); } Here's the problem. This does not create a file in the web root, it creates it in the directory where the webdav server is running. When i run this on an IIS server it seems to do nothing at all (at least not that i can tell). How can I get a handle to the webroot programmatically so that i can place the resultant file there and then return the public URL? I can tack on the domain name after the fact without issue so if it only returns the relative path to the file that's fine. Thanks, brian

    Read the article

  • File size monitoring in C#

    - by manemawanna
    Hello, I work in the Systems & admin team and have been given the task of creating a quota management application to try and encourage users to better manage there resources as we currently have issues with disc space and don't enforce hard quotas. At the moment I'm using the code below to go through all the files in a users homespace to retrieve the overall amount of space they are using. As from what I've seen else where theres no other way to do this in C#, the issue with it is theirs quite a high overhead while it retireves the size of each file then creates a total. try { long dirSize = 0; FileInfo[] FI = new DirectoryInfo("I:\\").GetFiles("*.*", SearchOption.AllDirectories); foreach (FileInfo F1 in FI) { dirSize += F1.Length; } return dirSize; } So I'm looking for a quicker way to do this or a quick way to monitor changes in the size of files while using the options avaliable through FileSystemWatcher. At the moment the only thing I can think of is creating a hashtable containing the file location and size of each file, so when a size changed event occurs I can compare the old size against the new one and update the total. Any suggestions would be greatly appreciated.

    Read the article

  • c programming malloc question

    - by user535256
    Hello guys, Just got query regarding c malloc() function. I am read()ing x number of bytes from a file to get lenght of filename, like ' read(file, &namelen, sizeof(unsigned char)); ' . The variable namelen is a type unsigned char and was written into file as that type (1 byte). Now namelen has the lenght of filename ie namelen=8 if file name was 'data.txt', plus extra /0 at end, that working fine. Now I have a structure recording file info, ie filename, filelenght, content size etc. struct fileinfo { char *name; ...... other variable like size etc }; struct fileinfo *files; Question: I want to make that files.name variable the size of namelen ie 8 so I can successfully write the filename into it, like ' files[i].name = malloc(namelen) ' However, I dont want it to be malloc(sizeof(namelen)) as that would make it file.name[1] as the size of its type unsigned char. I want it to be the value thats stored inside variable &namelen ie 8 so file.name[8] so data.txt can be read() from file as 8 bytes and written straight into file.name[8? Is there a way to do this my current code is this and returns 4 not 8 files[i].name = malloc(namelen); //strlen(files[i].name) - returns 4 //perhaps something like malloc(sizeof(&namelen)) but does not work Thanks for any suggestions Have tried suggested suggestions guys, but I now get a segmentation fault error using: printf("\nsizeofnamelen=%x\n",namelen); //gives 8 for data.txt files[i].name = malloc(namelen + 1); read(file, &files[i].name, namelen); int len=strlen(files[i].name); printf("\nnamelen=%d",len); printf("\nname=%s\n",files[i].name); When I try to open() file with that files[i].name variable it wont open so the data does not appear to be getting written inside the read() &files[i].name and strlen() causes segemntation error as well as trying to print the filename

    Read the article

  • breadth-first traversal of directory tree is not lazy

    - by user855443
    I try to traverse the diretory tree. A naive depth-first traversal seems not to produce the data in a lazy fashion and runs out of memory. I next tried a breadth first approach, which shows the same problem - it uses all the memory available and then crashes. the code i have is: getFilePathBreadtFirst :: FilePath -> IO [FilePath] getFilePathBreadtFirst fp = do fileinfo <- getInfo fp res :: [FilePath] <- if isReadableDirectory fileinfo then do children <- getChildren fp lower <- mapM getFilePathBreadtFirst children return (children ++ concat lower) return (children ++ concat () else return [fp] -- should only return the files? return res getChildren :: FilePath -> IO [FilePath] getChildren path = do names <- getUsefulContents path let namesfull = map (path </>) names return namesfull testBF fn = do -- crashes for /home/frank, does not go to swap fps <- getFilePathBreadtFirst fn putStrLn $ unlines fps I think all the code is either linear or tail recursive, and I would expect that the listing of filenames starts immediately, but in fact it does not. Where is the error in my code and my thinking? where have I lost lazy evaluation?

    Read the article

  • Installing Zend on CentOS is having dependency issues

    - by rax
    I'm trying to install PHP's Zend Server on my CentOS VPS but it's having dependency issues that I can't seem to resolve. zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-gui-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-dev-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) knowledgetree-ce-3.7.0-2.noarch from KTnoarch has depsolving problems --> Missing Dependency: php-5.2-xmlrpc-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) knowledgetree-ce-3.7.0-2.noarch from KTnoarch has depsolving problems --> Missing Dependency: php-5.2-fileinfo-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-zend-extensions is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-common-extensions-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-fileinfo-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) Error: Missing Dependency: php-5.2-xmlrpc-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) Error: Missing Dependency: php-5.2-gui-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-common-extensions-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-dev-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-zend-extensions is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) When consulting the Google, all I get told is how to install PHP 5.2.* on CentOS. According to the output of php -v, I've done that. PHP 5.2.8 (cli) (built: Sep 28 2009 15:37:15) Copyright (c) 1997-2008 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies with the ionCube PHP Loader v3.1.34, Copyright (c) 2002-2009, by ionCube Ltd. How can I solve this issue?

    Read the article

  • Apache2 & .htaccess : Apache ignoring AccessFile

    - by Elyx0
    Hi there here is my server configuration: DEBIAN 32Bits / PHP 5 / Apache Server version: Apache/2.2.3 - Server built: Mar 22 2008 09:29:10 The AccessFiles : grep -ni AccessFileName * apache2.conf:134:AccessFileName .htaccess apache2.conf:667:AccessFileName .httpdoverride All the AllowOverride statements in my apache2/ folder. mods-available/userdir.conf:6: AllowOverride Indexes AuthConfig Limit mods-available/userdir.conf:16: AllowOverride FileInfo AuthConfig Limit mods-enabled/userdir.conf:6: AllowOverride Indexes AuthConfig Limit mods-enabled/userdir.conf:16: AllowOverride FileInfo AuthConfig Limit sites-enabled/default:8: AllowOverride All sites-enabled/default:14: AllowOverride All sites-enabled/default:19: AllowOverride All sites-enabled/default:24: AllowOverride All sites-enabled/default:42: AllowOverride All The sites-enabled/default file : 1 <VirtualHost *> 2 ServerAdmin [email protected] 3 ServerName mysite.com 4 ServerAlias mysite.com 5 DocumentRoot /var/www/mysite.com/ 6 <Directory /> 7 Options FollowSymLinks 8 AllowOverride All 9 Order Deny,Allow 10 Deny from all 11 </Directory> 12 <Directory /var/www/mysite.com/> 13 Options Indexes FollowSymLinks MultiViews 14 AllowOverride All 15 Order allow,deny 16 allow from all 17 </Directory> 18 <Directory /var/www/mysite.com/test/> 19 AllowOverride All 20 </Directory> 21 22 ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ 23 <Directory "/usr/lib/cgi-bin"> 24 AllowOverride All 25 Options ExecCGI -MultiViews +SymLinksIfOwnerMatch 26 Order allow,deny 27 Allow from all 28 </Directory> 29 30 ErrorLog /var/log/apache2/error.log 31 32 # Possible values include: debug, info, notice, warn, error, crit, 33 # alert, emerg. 34 LogLevel warn 35 36 CustomLog /var/log/apache2/access.log combined 37 ServerSignature Off 38 39 Alias /doc/ "/usr/share/doc/" 40 <Directory "/usr/share/doc/"> 41 Options Indexes MultiViews FollowSymLinks 42 AllowOverride All 43 Order deny,allow 44 Deny from all 45 Allow from 127.0.0.0/255.0.0.0 ::1/128 46 </Directory> 47 48 49 50 51 52 53 54 </VirtualHost> If i change any Allow from all in Deny from all , it works whenever i put it. I've got one .htaccess at /mysite.com/.htaccess & one at /mysite.com/test/.htaccess with: Order Deny,Allow Deny from all Neither of them work i can still see my website. I've got mod_rewrite enabled but i don't think it does anything here. I've tried almost everything :/ It works on my local environnement (MAMP) but fails when on my Debian server.

    Read the article

  • Installing Zend on CentOS is having dependency issues

    - by rax
    I'm trying to install PHP's Zend Server on my CentOS VPS but it's having dependency issues that I can't seem to resolve. zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-gui-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-dev-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) knowledgetree-ce-3.7.0-2.noarch from KTnoarch has depsolving problems --> Missing Dependency: php-5.2-xmlrpc-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) knowledgetree-ce-3.7.0-2.noarch from KTnoarch has depsolving problems --> Missing Dependency: php-5.2-fileinfo-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-zend-extensions is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) zend-server-php-5.2-4.0-73.noarch from Zend_noarch has depsolving problems --> Missing Dependency: php-5.2-common-extensions-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-fileinfo-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) Error: Missing Dependency: php-5.2-xmlrpc-zend-server is needed by package knowledgetree-ce-3.7.0-2.noarch (KTnoarch) Error: Missing Dependency: php-5.2-gui-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-common-extensions-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-dev-zend-server is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) Error: Missing Dependency: php-5.2-zend-extensions is needed by package zend-server-php-5.2-4.0-73.noarch (Zend_noarch) When consulting the Google, all I get told is how to install PHP 5.2.* on CentOS. According to the output of php -v, I've done that. PHP 5.2.8 (cli) (built: Sep 28 2009 15:37:15) Copyright (c) 1997-2008 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies with the ionCube PHP Loader v3.1.34, Copyright (c) 2002-2009, by ionCube Ltd. How can I solve this issue?

    Read the article

  • Apache2 & .htaccess : Apache ignoring AccessFile

    - by Elyx0
    Hi there here is my server configuration: DEBIAN 32Bits / PHP 5 / Apache Server version: Apache/2.2.3 - Server built: Mar 22 2008 09:29:10 The AccessFiles : grep -ni AccessFileName * apache2.conf:134:AccessFileName .htaccess apache2.conf:667:AccessFileName .httpdoverride All the AllowOverride statements in my apache2/ folder. mods-available/userdir.conf:6: AllowOverride Indexes AuthConfig Limit mods-available/userdir.conf:16: AllowOverride FileInfo AuthConfig Limit mods-enabled/userdir.conf:6: AllowOverride Indexes AuthConfig Limit mods-enabled/userdir.conf:16: AllowOverride FileInfo AuthConfig Limit sites-enabled/default:8: AllowOverride All sites-enabled/default:14: AllowOverride All sites-enabled/default:19: AllowOverride All sites-enabled/default:24: AllowOverride All sites-enabled/default:42: AllowOverride All The sites-enabled/default file : 1 <VirtualHost *> 2 ServerAdmin [email protected] 3 ServerName mysite.com 4 ServerAlias mysite.com 5 DocumentRoot /var/www/mysite.com/ 6 <Directory /> 7 Options FollowSymLinks 8 AllowOverride All 9 Order Deny,Allow 10 Deny from all 11 </Directory> 12 <Directory /var/www/mysite.com/> 13 Options Indexes FollowSymLinks MultiViews 14 AllowOverride All 15 Order allow,deny 16 allow from all 17 </Directory> 18 <Directory /var/www/mysite.com/test/> 19 AllowOverride All 20 </Directory> 21 22 ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ 23 <Directory "/usr/lib/cgi-bin"> 24 AllowOverride All 25 Options ExecCGI -MultiViews +SymLinksIfOwnerMatch 26 Order allow,deny 27 Allow from all 28 </Directory> 29 30 ErrorLog /var/log/apache2/error.log 31 32 # Possible values include: debug, info, notice, warn, error, crit, 33 # alert, emerg. 34 LogLevel warn 35 36 CustomLog /var/log/apache2/access.log combined 37 ServerSignature Off 38 39 Alias /doc/ "/usr/share/doc/" 40 <Directory "/usr/share/doc/"> 41 Options Indexes MultiViews FollowSymLinks 42 AllowOverride All 43 Order deny,allow 44 Deny from all 45 Allow from 127.0.0.0/255.0.0.0 ::1/128 46 </Directory> 47 48 49 50 51 52 53 54 </VirtualHost> If i change any Allow from all in Deny from all , it works whenever i put it. I've got one .htaccess at /mysite.com/.htaccess & one at /mysite.com/test/.htaccess with: Order Deny,Allow Deny from all Neither of them work i can still see my website. I've got mod_rewrite enabled but i don't think it does anything here. I've tried almost everything :/ It works on my local environnement (MAMP) but fails when on my Debian server.

    Read the article

  • nginx can't see MySQL

    - by user135235
    I have a fully working Joomla 2.5.6 install driven by a local MySQL server, but I'd like to test nginx to see if it's a faster web serving experience than Apache. \ PHP 5.4.6 (PHP54w) \ CentOS 6.2 \ Joomla 2.5.6 \ PHP54w-fpm.i386 (FastCGI process manager) \ php -m shows: mysql & mysqli modules loaded Nginx seems to have installed fine via yum, it can process a PHP-info file via FastCGI perfectly OK (http://37.128.190.241/php.php) but when I stop Apache, start nginx instead and visit my site I get: "Database connection error (1): The MySQL adapter 'mysqli' is not available." I've tried adjusting my Joomla configuration.php to use mysql instead of mysqli but I get the same basic error, only this time "Database connection error (1): The MySQL adapter 'mysql' is not available" of course! Can anyone think what the problem might be please? I did try explicitly setting extension = mysqli.so and extension = mysql.so in my php.ini to try and force the issue (despite php -m showing they were both successfully loaded anyway) - no difference. I have a pretty standard nginx default.conf: server { listen 80; server_name www.MYDOMAIN.com; server_name_in_redirect off; access_log /var/log/nginx/localhost.access_log main; error_log /var/log/nginx/localhost.error_log info; root /var/www/html/MYROOT_DIR; index index.php index.html index.htm default.html default.htm; # Support Clean (aka Search Engine Friendly) URLs location / { try_files $uri $uri/ /index.php?q=$uri&$args; } # deny running scripts inside writable directories location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ { return 403; error_page 403 /403_error.html; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi.conf; } # caching of files location ~* \.(ico|pdf|flv)$ { expires 1y; } location ~* \.(js|css|png|jpg|jpeg|gif|swf|xml|txt)$ { expires 14d; } } Snip of output from phpinfo under nginx: Server API FPM/FastCGI Virtual Directory Support disabled Configuration File (php.ini) Path /etc Loaded Configuration File /etc/php.ini Scan this dir for additional .ini files /etc/php.d Additional .ini files parsed /etc/php.d/curl.ini, /etc/php.d/fileinfo.ini, /etc/php.d/json.ini, /etc/php.d/phar.ini, /etc/php.d/zip.ini Snip of output from phpinfo under Apache: Server API Apache 2.0 Handler Virtual Directory Support disabled Configuration File (php.ini) Path /etc Loaded Configuration File /etc/php.ini Scan this dir for additional .ini files /etc/php.d Additional .ini files parsed /etc/php.d/curl.ini, /etc/php.d/fileinfo.ini, /etc/php.d/json.ini, /etc/php.d/mysql.ini, /etc/php.d/mysqli.ini, /etc/php.d/pdo.ini, /etc/php.d/pdo_mysql.ini, /etc/php.d/pdo_sqlite.ini, /etc/php.d/phar.ini, /etc/php.d/sqlite3.ini, /etc/php.d/zip.ini Seems that with Apache, PHP is loading substantially more additional .ini files, including ones relating to mysql (mysql.ini, mysqli.ini, pdo_mysql.ini) than nginx. Any ideas how I get nginix to also call these additional .ini's ? Thanks in advance, Steve

    Read the article

  • Issues with configuration of Apache and mod_auth_sspi

    - by TekiusFanatikus
    I've been able to get this working using XAMP with Apache 2.0.55 and XAMP Apache 2.2.14 without any problems. However, when I attempt to configure our intranet server (Apache 2.0.59), I don't get the same results. The results are that the following variables contain the information desired: $_SERVER["REMOTE_USER"] AND $_SERVER["PHP_AUTH_USER"]. In this case, they are blank. I'm expecting "domain/user_name". Conf file stuff: <Directory "/xxx/xampp/htdocs/"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # #Options Indexes FollowSymLinks Includes ExecCGI Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # #AllowOverride All AllowOverride None # # Controls who can get stuff from this server. # #Order allow,deny #Allow from all Order allow,deny Allow from all #NT Domain Login AuthName "Intranet" AuthType SSPI SSPIAuth On SSPIAuthoritative On SSPIDomain "xxxx" SSPIOfferBasic Off SSPIPerRequestAuth On SSPIOmitDomain Off # keep domain name in userid string SSPIUsernameCase lower Require valid-user </Directory> I would like to note that I've modified the paths to reflect the intranet environment. I'm using the following module: http://sourceforge.net/projects/mod-auth-sspi/ Once the module is installed and the conf file is modified, the intranet environment's server scope isn't populated with the expected variables. Edit #1 <Directory "/path_here"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # #Options Indexes FollowSymLinks Includes ExecCGI Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # #AllowOverride All AllowOverride None # # Controls who can get stuff from this server. # #Order allow,deny #Allow from all Order allow,deny Allow from all #NT Domain Login AuthName "Intranet" AuthType SSPI SSPIAuth On SSPIAuthoritative On SSPIDomain "domain_here" SSPIOfferBasic On SSPIPerRequestAuth On SSPIOmitDomain Off # keep domain name in userid string SSPIUsernameCase lower Require valid-user </Directory>

    Read the article

  • How can I run a PowerShell function remotely?

    - by Aimar
    Using powershell, I plan to run many functions on a remote host to gather information. Here is an example to retrieve the content of file remotely just by running a function called getcontentfile with the parameter as the name of the remote host: function getcontentfile { [CmdletBinding()] param($hostname) $info = Get-Content "C:\fileinfo.xml" write-host $info } This function should return information about the remote host to the local instance of PowerShell. How can I modify this script to do that?

    Read the article

  • add a from to backup routine

    - by Gerard Flynn
    hi how do you put a process bar and button onto this code i have class and want to add a gui on to the code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; using System.Threading; using Tamir.SharpSsh; using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.GZip; namespace backup { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// Summary description for Class1. /// </summary> public class Backup { private string dbName; private string dbUsername; private string dbPassword; private static string baseDir; private string backupName; private static bool isBackup; private string keyString; private string ivString; private string[] backupDirs = new string[0]; private string[] excludeDirs = new string[0]; private ZipOutputStream zipOutputStream; private string backupFile; private string zipFile; private string encryptedFile; static void Main() { Backup.Log("BackupUtility loaded"); try { new Backup(); if (!isBackup) MessageBox.Show("Restore complete"); } catch (Exception e) { Backup.Log(e.ToString()); if (!isBackup) MessageBox.Show("Error restoring!\r\n" + e.Message); } } private void LoadAppSettings() { this.backupName = System.Configuration.ConfigurationSettings.AppSettings["BackupName"].ToString(); this.dbName = System.Configuration.ConfigurationSettings.AppSettings["DBName"].ToString(); this.dbUsername = System.Configuration.ConfigurationSettings.AppSettings["DBUsername"].ToString(); this.dbPassword = System.Configuration.ConfigurationSettings.AppSettings["DBPassword"].ToString(); //default to using where we are executing this assembly from Backup.baseDir = System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.LastIndexOf("\\")) + "\\"; Backup.isBackup = bool.Parse(System.Configuration.ConfigurationSettings.AppSettings["IsBackup"].ToString()); this.keyString = System.Configuration.ConfigurationSettings.AppSettings["KeyString"].ToString(); this.ivString = System.Configuration.ConfigurationSettings.AppSettings["IVString"].ToString(); this.backupDirs = GetSetting("BackupDirs", ','); this.excludeDirs = GetSetting("ExcludeDirs", ','); } private string[] GetSetting(string settingName, char delimiter) { if (System.Configuration.ConfigurationSettings.AppSettings[settingName] != null) { string settingVal = System.Configuration.ConfigurationSettings.AppSettings[settingName].ToString(); if (settingVal.Length > 0) return settingVal.Split(delimiter); } return new string[0]; } public Backup() { this.LoadAppSettings(); if (isBackup) this.DoBackup(); else this.DoRestore(); Log("Finished"); } private void DoRestore() { System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog(); fileDialog.Title = "Choose .encrypted file"; fileDialog.Filter = "Encrypted files (*.encrypted)|*.encrypted|All files (*.*)|*.*"; fileDialog.InitialDirectory = Backup.baseDir; if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //string encryptedFile = GetFileName("encrypted"); string encryptedFile = fileDialog.FileName; string decryptedFile = this.GetDecryptedFilename(encryptedFile); //string originalFile = GetFileName("original"); this.Decrypt(encryptedFile, decryptedFile); //this.UnzipFile(decryptedFile, originalFile); } } //use the same filename as the backup except replace ".encrypted" with ".decrypted.zip" private string GetDecryptedFilename(string encryptedFile) { string name = encryptedFile.Substring(0, encryptedFile.LastIndexOf(".")); name += ".decrypted.zip"; return name; } private void DoBackup() { this.backupFile = GetFileName("bak"); this.zipFile = GetFileName("zip"); this.encryptedFile = GetFileName("encrypted"); this.DeleteFiles(); this.zipOutputStream = new ZipOutputStream(File.Create(zipFile)); try { //backup database first if (this.dbName.Length > 0) { this.BackupDB(backupFile); this.ZipFile(backupFile, this.GetName(backupFile)); } //zip any directories specified in config file this.ZipUserSpecifiedFilesAndDirectories(this.backupDirs); } finally { this.zipOutputStream.Finish(); this.zipOutputStream.Close(); } this.Encrypt(zipFile, encryptedFile); this.SCPFile(encryptedFile); this.DeleteFiles(); } /// <summary> /// Deletes any files created by the backup process, namely the DB backup file, /// the zip of all files backuped up, and the encrypred zip file /// </summary> private void DeleteFiles() { File.Delete(this.backupFile); File.Delete(this.zipFile); ///File.Delete(this.encryptedFile); } private void ZipUserSpecifiedFilesAndDirectories(string[] fileNames) { foreach (string fileName in fileNames) { string name = fileName.Trim(); if (name.Length > 0) { Log("Zipping " + name); this.ZipFile(name, this.GetNameFromDir(name)); } } } private void SCPFile(string inputPath) { string sshServer = System.Configuration.ConfigurationSettings.AppSettings["SSHServer"].ToString(); string sshUsername = System.Configuration.ConfigurationSettings.AppSettings["SSHUsername"].ToString(); string sshPassword = System.Configuration.ConfigurationSettings.AppSettings["SSHPassword"].ToString(); if (sshServer.Length > 0 && sshUsername.Length > 0 && sshPassword.Length > 0) { Scp scp = new Scp(sshServer, sshUsername, sshPassword); //Copy a file from local machine to remote SSH server scp.Connect(); Log("Connected to " + sshServer); //scp.Put(inputPath, "/home/wal/temp.txt"); scp.Put(inputPath, GetName(inputPath)); scp.Close(); } else { Log("Not SCP as missing login details"); } } private string GetName(string inputPath) { FileInfo info = new FileInfo(inputPath); return info.Name; } private string GetNameFromDir(string inputPath) { DirectoryInfo info = new DirectoryInfo(inputPath); return info.Name; } private static void Log(string msg) { try { string toLog = DateTime.Now.ToString() + ": " + msg; System.Diagnostics.Debug.WriteLine(toLog); System.IO.FileStream fs = new System.IO.FileStream(baseDir + "app.log", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End); m_streamWriter.WriteLine(toLog); m_streamWriter.Flush(); m_streamWriter.Close(); fs.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private byte[] GetFileBytes(string path) { FileStream stream = new FileStream(path, FileMode.Open); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); return bytes; } private void WriteFileBytes(byte[] bytes, string path) { FileStream stream = new FileStream(path, FileMode.Create); stream.Write(bytes, 0, bytes.Length); stream.Close(); } private void UnzipFile(string inputPath, string outputPath) { ZipInputStream zis = new ZipInputStream(File.OpenRead(inputPath)); ZipEntry theEntry = zis.GetNextEntry(); FileStream streamWriter = File.Create(outputPath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = zis.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); zis.Close(); } private bool ExcludeDir(string dirName) { foreach (string excludeDir in this.excludeDirs) { if (dirName == excludeDir) return true; } return false; } private void ZipFile(string inputPath, string zipName) { FileAttributes fa = File.GetAttributes(inputPath); if ((fa & FileAttributes.Directory) != 0) { string dirName = zipName + "/"; ZipEntry entry1 = new ZipEntry(dirName); this.zipOutputStream.PutNextEntry(entry1); string[] subDirs = Directory.GetDirectories(inputPath); //create directories first foreach (string subDir in subDirs) { DirectoryInfo info = new DirectoryInfo(subDir); string name = info.Name; if (this.ExcludeDir(name)) Log("Excluding " + dirName + name); else this.ZipFile(subDir, dirName + name); } //then store files string[] fileNames = Directory.GetFiles(inputPath); foreach (string fileName in fileNames) { FileInfo info = new FileInfo(fileName); string name = info.Name; this.ZipFile(fileName, dirName + name); } } else { Crc32 crc = new Crc32(); this.zipOutputStream.SetLevel(6); // 0 - store only to 9 - means best compression FileStream fs = null; try { fs = File.OpenRead(inputPath); } catch (IOException ioEx) { Log("WARNING! " + ioEx.Message);//might be in use, skip file in this case } if (fs != null) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(zipName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; this.zipOutputStream.PutNextEntry(entry); this.zipOutputStream.Write(buffer, 0, buffer.Length); } } } private void Encrypt(string inputPath, string outputPath) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); byte[] encrypted; byte[] toEncrypt; //Create a new key and initialization vector. //myRijndael.GenerateKey(); //myRijndael.GenerateIV(); /*des.GenerateKey(); des.GenerateIV(); string temp1 = Convert.ToBase64String(des.Key); string temp2 = Convert.ToBase64String(des.IV);*/ //Get the key and IV. byte[] key = Convert.FromBase64String(keyString); byte[] IV = Convert.FromBase64String(ivString); //Get an encryptor. ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(key, IV); //Encrypt the data. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); //Convert the data to a byte array. toEncrypt = this.GetFileBytes(inputPath); //Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. encrypted = msEncrypt.ToArray(); WriteFileBytes(encrypted, outputPath); } private void Decrypt(string inputPath, string outputPath) { RijndaelManaged myRijndael = new RijndaelManaged(); //DES des = new DESCryptoServiceProvider(); byte[] key = Convert.FromBase64String(keyString); byte[] IV = Convert.FromBase64String(ivString); byte[] encrypted = this.GetFileBytes(inputPath); byte[] fromEncrypt; //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); fromEncrypt = new byte[encrypted.Length]; //Read the data out of the crypto stream. int bytesRead = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); byte[] readBytes = new byte[bytesRead]; Array.Copy(fromEncrypt, 0, readBytes, 0, bytesRead); this.WriteFileBytes(readBytes, outputPath); } private string GetFileName(string extension) { return baseDir + backupName + "_" + DateTime.Now.ToString("yyyyMMdd") + "." + extension; } private void BackupDB(string backupPath) { string sql = @"DECLARE @Date VARCHAR(300), @Dir VARCHAR(4000) --Get today date SET @Date = CONVERT(VARCHAR, GETDATE(), 112) --Set the directory where the back up file is stored SET @Dir = '"; sql += backupPath; sql += @"' --create a 'device' to write to first EXEC sp_addumpdevice 'disk', 'temp_device', @Dir --now do the backup BACKUP DATABASE " + this.dbName; sql += @" TO temp_device WITH FORMAT --Drop the device EXEC sp_dropdevice 'temp_device' "; //Console.WriteLine("sql="+sql); Backup.Log("Starting backup of " + this.dbName); ExecuteSQL(sql); } /// <summary> /// Executes the specified SQL /// Returns true if no errors were encountered during execution /// </summary> /// <param name="procedureName"></param> private void ExecuteSQL(string sql) { SqlConnection conn = new SqlConnection(this.GetDBConnectString()); try { SqlCommand comm = new SqlCommand(sql, conn); conn.Open(); comm.ExecuteNonQuery(); } finally { conn.Close(); } } private string GetDBConnectString() { StringBuilder builder = new StringBuilder(); builder.Append("Data Source=127.0.0.1; User ID="); builder.Append(this.dbUsername); builder.Append("; Password="); builder.Append(this.dbPassword); builder.Append("; Initial Catalog="); builder.Append(this.dbName); builder.Append(";Connect Timeout=30"); return builder.ToString(); } } } }

    Read the article

  • Bugzilla ./testserver.pl failing

    - by SomeKittens
    root@KittensTest:/var/www/Bugzilla/bugzilla-4.2.1# ./testserver.pl http://localhost/Bugzilla/bugzilla-4.2.1 TEST-OK Webserver is running under group id in $webservergroup. TEST-OK Got padlock picture. TEST-FAILED Webserver is fetching rather than executing CGI files. Check the AddHandler statement in your httpd.conf file. Well then. httpd.conf (from here[2.2.4.1.1]): <Directory /var/www/Bugzilla/bugzilla-4.2.1> AddHandler cgi-script .cgi .pl Options +Indexes +Includes +ExecCGI DirectoryIndex index.cgi AllowOverride Limit FileInfo Indexes </Directory> What am I doing wrong? I'm pretty new to this (first Bugzilla install), so I'll appreciate explanation.

    Read the article

  • Convert Excel File 'xls' to CSV, CAUTION: Bumps Ahead

    - by faizanahmad
    The task was to provide users with an interface where they can upload the 'csv' files, these files were to be processed and loaded to Database by a Console application. The code in Console application could not handle the 'xls' files so we thought, OK, lets convert 'xls' to 'csv' in the code, Seemed like fun. The idea was to convert it right after uploading within 'csv' file. As Microsoft does not recommend using the  Excel objects in ASP.NET, we decided to use the Jet engine to open xls. (Ace driver is used for xlsx) The code was pretty straight, can be found on following links: http://www.c-sharpcorner.com/uploadfile/yuanwang200409/102242008174401pm/1.aspx http://www.devasp.net/net/articles/display/141.html FIRST BUMP 'OleDbException (0x80004005): Unspecified error' ( Impersonation ): The ablove code ran fine in my test web site and test console application, but it gave an 'OleDbException (0x80004005): Unspecified error' in main web site, turns out imperonation was set to True and as soon as I changed it to False, it did work. on My XP box, web site was running under user                   'ASPNET'  with imperosnation set to FALSE                   'IUSR_*' i.e IIS guest user with impersonation set to TRUE The weired part was that both users had same rights on the folders I was saving files to and on Excel app in DCOM Config.  We decided to give it a try on Windows Server 2003 with web site set to windows authentication ( impersonation = true ) and yes it did work. SECOND BUMP 'External table not in correct format': I got this error with some files and it appeared that the file from client has some metadata issues  ( when I opened the file in Excel and try to save it ,excel  would give me this error saying File can not be saved in current format ) and the error was caused by that. Some people were able to reslove the error by using "Extended Properties=HTML Import;" in connection string. But it did not work for me. We decided to detour from here and use Excel object :( as we had no control on client setting the meta deta of Excel files. Before third bump there were a ouple of small thingies like 'Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005' Fix can be found at http://blog.crowe.co.nz/archive/2006/03/02/589.aspx THIRD BUMP ( Could not get rid of the EXCEL process  ):  I has all the code in place to 'Quiet' the excel, but, it just did not work. work around was done to Kill the process as we knew no other application on server was using EXCEL.  The normal steps to quite the excel application worked just fine in console application though.   FOURTH BUMP: Code worked with one file 1 on my machine and with the other file 2 code will break. and the same code will work perfectly fine with file 2 on some other machine . We moved it to QA  ( Windows Server 2003 )and worked with every file just perfect. But , then there was another problem: one user can upload it and second cant, permissions on folder and DCOM Conifg checked. Another Detour: Uplooad the xls as it is and convert in Console application.   Lesson Learnt:  If its 'xlsx' use 'ACE Driver' or read xml within excel as recommneded by MS. If xls and you know its always going to be properly formatted  'jet Engine'  Code: Imports Microsoft.Office.Interop Private Function ConvertFile(ByVal SourceFolder As String, ByVal FileName As String, ByVal FileExtension As String)As Boolean     Dim appExcel As New Excel.Application     Dim workBooks As Excel.Workbooks = appExcel.Workbooks     Dim objWorkbook As Excel.Workbook      Try                   objWorkbook = workBooks.Open(CompleteFilePath )                            objWorkbook.SaveAs(Filename:=CObj(SourceFolder & FileName & ".csv"), FileFormat:=Excel.XlFileFormat.xlCSV)       Catch ex As Exception         GenerateAlert(ex.Message().Replace("'", "") & " Error Converting File to CSV.")         LogError(ex )         Return False      Finally                      If Not(objWorkbook is Nothing) then               objWorkbook.Close(SaveChanges:=CObj(False))           End If           ReleaseObj(objWorkbook)                                      ReleaseObj(workBooks)           appExcel.Quit()           ReleaseObj(appExcel)                                 Dim proc As System.Diagnostics.Process           For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")               proc.Kill()           Next         DeleteSourceFile(SourceFolder & FileName & FileExtension)     End Try  Return True  End Function   Private Sub ReleaseObj(ByVal o As Object)     Try      System.Runtime.InteropServices.Marshal.ReleaseComObject(o)   Catch ex As Exception           LogError(ex )   Finally      o = Nothing    End Try End Sub     Protected Sub DeleteSourceFile(Byval CompleteFilePath As string)         Try             Dim MyFile As FileInfo = New FileInfo(CompleteFilePath)             If  MyFile.Exists Then                 File.Delete(CompleteFilePath)             Else              Throw New FileNotFoundException()             End If         Catch ex As Exception             GenerateAlert( " Source File could not be deleted.")              LogError(ex)         End Try     End Sub  The code to kill the process ( Avoid it if you can ): Dim proc As System.Diagnostics.Process For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")     proc.Kill() Next

    Read the article

  • FluentPath: a fluent wrapper around System.IO

    .NET is now more than eight years old, and some of its APIs got old with more grace than others. System.IO in particular has always been a little awkward. Its mostly static method calls (Path.*, Directory.*, etc.) and some stateful classes (DirectoryInfo, FileInfo). In these APIs, paths are plain strings. Since .NET v1, lots of good things happened to C#: lambda expressions, extension methods, optional parameters to name just a few. Outside of .NET, other interesting things happened as well. For...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >