Roxy Fileman and Virtual Directorys - asp.net-mvc

I have a solution with 2 projects in, one called "admin", the other say "work" (an Umbraco instance)
- Work has an images folder which contains the images for the site
banners/thumnails etc.
- Admin allows an admin user to add new stories, with images, using TinyMCE
and the fileman plug in.
So in IIS I created a virtual folder in Admin which points to the images folder in work, however when I try and browse the folder in fileman it repeats lots of sub directoriers and doesnt display any images.And I cannot upload any images either, it just gives me an error.
The Files_Root entry is as follows within the conf.json file.
"FILES_ROOT": ".//images//",
So how do I get this virtual folder to work with fileman?

I stumbled upon this problem as well - when the FILES_ROOT points to a virtual folder in IIS, the Fileman component chokes when trying to retrieve the list of files, and when uploading, and maybe some other places. The requests don't pass the folder location properly when it references a virtual directory. If you put a network sniffer on it, you'll see the requests sent to fileman/asp_net/main.ashx and the responses that come back with the error "The given path's format is not supported."
I've reported the bug to the author via the website, but I have also discovered that if you replace the virtual directory with a SYMLINK, everything seems to work.
If you have IIS access, you probably have command line access to create the symlink, which can be done as:
mklink /j "{virtual location within your website}" "{physical location}"
Both locations should be full paths, including drive letters and the "virtual" location should be in your website root.
So far, I have not seen an problems referencing files this way instead of with a virtual directory, other than that my site backups started including the files in the symlink, since the O/S sees that as a physical folder within the site now.
I hope this helps!!

Probably not good for every situation (maybe not even for the user that asked the question), but figured I would share in case it might help someone trying to get virtual directories mapped to network shares working. I needed to modify the ListDirTree function in file fileman/asp_net/main.ashx
protected void ListDirTree(string type)
{
string filesRoot = GetFilesRoot();
DirectoryInfo d = new DirectoryInfo( filesRoot );
if ( !d.Exists )
throw new Exception( "Invalid files root directory. Check your configuration: " + filesRoot );
ArrayList dirs = ListDirs( d.FullName );
dirs.Insert( 0, d.FullName );
string localPath = _context.Server.MapPath( "~/" );
bool isLocal = filesRoot.Contains( ":" );
_r.Write( "[" );
for ( int i = 0; i < dirs.Count; i++ )
{
string dir = (string)dirs[i];
string lPath;
//If it is a local path, leave it as it was
if ( isLocal )
lPath = dir.Replace( localPath, "" ).Replace( "\\", "/" );
else
//Otherwise probably a virtual directory, put the original files_root location back
lPath = dir.Replace( filesRoot, GetSetting( "FILES_ROOT" ) ).Replace( "\\", "/" );
_r.Write( "{\"p\":\"/" + lPath + "\",\"f\":\"" + GetFiles( dir, type ).Count.ToString() + "\",\"d\":\"" + Directory.GetDirectories( dir ).Length.ToString() + "\"}" );
if ( i < dirs.Count - 1 )
_r.Write( "," );
}
_r.Write( "]" );
}

Related

I changed the ownership of one of my google drive folders, but it still consumes from my storage

My google drive storage is running out of space. So, in order to free some space, I created a new google account and transferred the ownership of one of the largest folders in my original drive (~7 GB) to the new account's drive.
The problem is, that after 3 days of waiting, the folder is still consuming the storage of the original account's drive. I made sure that the new account is the owner of the folder, but the problem is still there.
Any ideas?
The problem is that changing the ownership of folder inside google drive does not change it for the subfolders and files, you have to change them separately or write an app script to search for file and subfolders owned by you and change the ownership.
Run the script below as your account, if you are using Google Workspace and you are the admin and need to do it to other accounts, then you need to get a service account first and run the code below.
Note:
This way makes a lot of noise with notifications on both sides, the old owner and the new one.
function ChangeFileOwnership(folder){
// New owner
var new_owner = '<Add new owner email>';
if (folder == null) {
var folderObj = DriveApp.getFolderById('<ID of parent folder>');
return ChangeFileOwnership(folderObj);
}
var fileIt = folder.searchFiles('"me" in owners');
while (fileIt.hasNext()) {
var file = fileIt.next();
Logger.log("Changing ownership of " + file.getName() + " to " + new_owner);
// Set the owner to be the new owner
try {
file.addEditor(new_owner);
}
catch(err){
Logger.log(err.message);
}
try {
file.setOwner(new_owner);
}
catch(err){
Logger.log(err.message);
}
}
// Get all the sub-folders and iterate
var folderIt = folder.getFolders();
while (folderIt.hasNext()) {
fs = ChangeFileOwnership(folderIt.next());
}
}

Hyperlinking a folder stored on iManage

I'm looking for a way to create a hyperlink to a particular folder in Worksite.
So far, I've only come up with a macro linking files on the basis of their database numbers but folders do not have database numbers (I think).
Another thing is that I wanted the folders to be opened in Outlook (Worksite is connected with Outlook and we access folders through it)
What I try to accomplish is creating hyperlinks in Excel for easy folder access (just like hyperlinks to files).
Does anybody have a clue if it's even possible? If yes, I'd appreciate an example of a code for this.
Thanks in advance.
Yes it's possible.
You don't mention which version of the iManage client you're working with however I'm going to assume FileSite 9.x. Installed with that client is a custom protocol handler which supports a custom URI scheme.
In effect this allows you to compose a hyperlink with plain text which you can then embed in your web page, or just start a new process in Windows to let the default browser load it up.
The custom protocol handler will parse it and then start up whatever iManage client it can (FileSite in your case) and then navigate to the correct folder.
Format is iwl:dms=[ServerName]&&lib=[DatabaseName]&&page=[FolderID]
Here's some C# that builds out such a string
var serverName = "MYSERVERNAME";
var databaseName = "MYDBNAME";
var serverName = "1234"; // internal numeric ID of folder (MHGROUP.PROJECTS.PRJ_ID in database, or IManFolder.FolderID via iManage COM API object model
var sb = new StringBuilder("iwl:");
sb.Append($"dms={serverName}");
sb.Append("&&");
sb.Append($"lib={databaseName}");
sb.Append("&&");
sb.Append($"page={serverName}");
// sb.ToString() will now output the hyperlink reference to your folder which you can pass to your web browser..
Sub Folder_link
Dim dmsIM As IManDMS
Dim dmsS As IManSession
Dim dmsD As IManDatabase
Dim FdR As IManFolder
Dim FdrLoc As String
Dim FdrID As Long
Const ServerName As String = <DMS name>
Const DatabaseName As String = <DatabaseName>
FdrLoc = "\\{DMS name}\{DatabaseName}\Main Folder\SubFolder\SubSubFolder\TargetFolderName"
Set dmsIM = New ManDMS
Set dmsS = dmsIM.Sessions.Add(ServerName)
dmsS.TrustedLogin
Set dmsD = dmsS.Databases.ItemByName(DatabaseName)
Set Fdr = Imanage.ImanFolder.Location (FdrLoc)
FdrID = Fdr.FolderID
With ThisWorkBook.WorkSheets(1).Range("A1")
.Hyperlinks.Add _
Anchor:=Selection, _
Address:="iwl:dms={serverName}&&lib={databaseName}&&page=" & FdrID, _
TextToDisplay:="link"
End With
End Sub

MVC download images from ftp and show in VIew

Have some pictures on ftp location. My controller is getting list of paths for some specific images placed on ftp. What i want to do is to use those paths to download those pictures to local temporary folder and then show them inside gallery in view. Currently i am struggling with model to download those pictures but have some problems when trying to download pictures. Error posted below as well as current code. There is also folder creation code missing.
This is my controller method which would get paths list then calling download method to download pictures from ftp location to some temporary folder (and this temporary folder should be besides my application that then view could open images from that folder:
Function Details(Optional ByVal id As Long = Nothing) As ActionResult
'--Temporary directory for pictures to be downloaded from ftp location (temp_dir) should be created besides application folders
Dim temp_dir As String = "/temp_dir/"
'--If not temp_dir exist ==> create this folder
'--if folder has been created properly go all next lines..
'--Take list of all ftp paths e.g \someFolderForPictures\image1.jpg to be downloaded to temp_dir
Dim PicsTrans As List(Of tblTransPics) = db.tblTransPics.Where(Function(f) f.IdTrans = id).ToList
'--For each picture path download it to temp_dir folder with temporary name
For Each imgFtpPath In PicsTrans
Dim temp_picName As String = Guid.NewGuid.ToString
DownloadFile(imgFtpPath.PicturePath, temp_dir & temp_picName)
Next
'-- If everythings went well - pass either temp_dir path to view and inside view those pictures will be opened or pass list of pictures (bytes)???
Return View(temp_dir)
End Function
Download file method:
Public Function DownloadFile(ByVal ftpPicLocation As String, destinationLocation As String) As Boolean
Dim reqFTP As FtpWebRequest
Try
reqFTP = DirectCast(FtpWebRequest.Create("ftp://someftpserver.com" & ftpPicLocation), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("myusername", "somepassword")
Using outputStream As New FileStream(destinationLocation, FileMode.OpenOrCreate)
Using response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
Using ftpStream As Stream = response.GetResponseStream()
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
End Using
End Using
End Using
Return True
Catch ex As Exception
Throw New Exception("Failed to download", ex.InnerException)
End Try
End Function
the error occurs on this line:
Using outputStream As New FileStream(destinationLocation, FileMode.OpenOrCreate)
and it says:
Cannot find part of path „C:\temp_dir\f0f43089-4a16-4229-8ea6-2c3a55fde2ae”.
By the way how there could be C:\ ?
Remove first slash in your temp_dir variable.
Dim temp_dir As String = "temp_dir/"
With this slash it means you want to write into your root. Your root equals C:\
By removing the first slash you get your temporary folder under the folder your application is running.

Magento multilanguage - double change in language resuts in 404 (or how to change language within stores not views)

I have a problem with a magento installation. I used Magento ver. 1.5.0.1, community edition to develop this website http://cissmarket.com/.
The problem appears when I change the language from the EU version to French and after that to German. The change to french is ok, but when in the same page i change to German i receive a 404 error. Also this is generation 404 errors in the Google webmaster tools and when i try for example to take this link and paste it in the browser it gives me also a 404 error. I have there some 50 products and ~550 404 errors in Google Webmaster tools. I understand that the problem is from what I described.
Moreover I have a SEO problem since I have this page in french:
http://cissmarket.com/de/cartouches-refilables.html
And when I switch to the german version of the website it takes me to this link
http://cissmarket.com/de/cartouches-refilables.html?___from_store=fr (if i try now to switch to uk I will get the 404 mentioned above)
instead of going to this one:
http://cissmarket.com/de/nachfullpatronen.html
Already checked this 404 error when switching between stores when in a category on magento but it does not relate to my problem.
About settings:
I use the caching service and also I did index all the content.
The product or category I am trying to access is available and set active for all the languages.
System > General > Web > URL options > Add Store Code to Urls is set
to yes.
System > General > Web > Search Engines Optimization > Use Web Server
Rewrites is set to yes.
No other changes has been made to the .htaccess file except for the
ones that the system itself made.
So to conclude: the problem is the 404 given by 2 succesive changes of the language and the bad url address when I switch from one page to another.
Any suggestions would be appreciated.
UPDATE: tried this http://www.activo.com/how-to-avoid-the-___from_store-query-parameter-when-switching-store-views-in-magento but it results in a 404 at the first language change
Edit #1:
Found the problem: file languages.phtml contained this code <?php echo str_replace ("/fr/","/de/",$_lang->getCurrentUrl()); ?> and actually did replace only the language code and not the whole url according to the corresponding translation.
So applied to this
http://cissmarket.com/fr/cartouches-refilables.html
it will return
http://cissmarket.com/de/cartouches-refilables.html
So does anyone know how to get the corresponding URL of the current page for the other languages available in the store?
Edit #2 (using #Vinai solution):
It works on the product pages but not on the category yet.
There is no such thing in the native Magento as far as I know.
That said, you can use the following code to get the current page URL for each store.
$resource = Mage::getSingleton('core/resource');
$requestPath = Mage::getSingleton('core/url')->escape(
trim(Mage::app()->getRequest()->getRequestString(), '/')
);
$select = $resource->getConnection('default_read')->select()
->from(array('c' => $resource->getTableName('core/url_rewrite')), '')
->where('c.request_path=?', $requestPath)
->where('c.store_id=?', Mage::app()->getStore()->getId())
->joinInner(
array('t' => $resource->getTableName('core/url_rewrite')),
"t.category_id=c.category_id AND t.product_id=c.product_id AND t.id_path=c.id_path",
array('t.store_id', 't.request_path')
);
$storeUrls = (array) $resource->getConnection('default_read')
->fetchPairs($select);
This will give you an array with the array key being the store IDs and the array values being the request path after the Magento base URL, e.g. assuming your French store has the ID 1 and the German one has the ID 2, you would get:
Array
(
[1] => cartouches-refilables.html
[2] => nachfullpatronen.html
)
Then, in the foreach loop where the URL for each store is output, use
<?php $url = isset($storeUrls[$_lang->getId()]) ? $_lang->getUrl($storeUrls[$_lang->getId()]) : $_lang->getCurrentUrl() ?>
The call to $_lang->getUrl() will add the base URL, so you will get the full URL for each store (e.g. http://cissmarket.com/de/nachfullpatronen.html). If no store view value is found in the core_url_rewrite table it will revert to the default behaviour.
You still need the ___store=fr query parameter because otherwise Magento will think you are trying to access the new path in the context of the old store. Luckily, the getUrl() call an the store model adds that for you automatically.
The code querying the database can be anywhere of course (since its PHP), even in the template, but please don't put it there. The correct place to have code that access the database is a resource model. I suggest you create a resource model and put it in a method there.
I've found an ugly patch until a better approach comes up.
In the admin section, i've added the following javascript inside the wysiwyg in CMS > PAGES > (My 404 pages) (at the beginning of the wysiwyg) :
<script type="text/javascript" language="javascript">// <![CDATA[
var lang = "en";
var rooturl = "{{config path="web/unsecure/base_url"}}"
var url = document.location.href;
if(!(url.match("/"+lang+"/")))
{
var newUrl = url.replace(rooturl , rooturl+lang+"/" );
window.location.href = newUrl;
}
// ]]></script>
(Note: you need to do this for all of your translated 404 pages. In each 404 page you need to modify lang="en" for your storeview url value)
Because the wysiwyg (tiny_mce) does not allow javascript to be threated, you'll have to modify js/mage/adminhtml/wysiwyg/tinymce/setup.js. Add the following code under line 97 (under "var settings = "):
extended_valid_elements : 'script[language|type|src]',
For Magento 1.7.0.2 and 1.8.0.0 this is the bugfix:
Starting from line 251 of /app/code/core/Mage/Core/Model/Url/Rewrite.php
:
Mage::app()->getCookie()->set(Mage_Core_Model_Store::COOKIE_NAME, $currentStore->getCode(), true);
// endur 02-03-2013 fix for missed store code
// $targetUrl = $request->getBaseUrl(). '/' . $this->getRequestPath();
if (Mage::getStoreConfig('web/url/use_store') && $storeCode = Mage::app()->getStore()>getCode()) {
$targetUrl = $request->getBaseUrl(). '/' . $storeCode . '/' .$this->getRequestPath();
} else {
$targetUrl = $request->getBaseUrl(). '/' . $this->getRequestPath();
}
// endur 02-03-2013 end
Make sure to create a custom copy of the file in:
/app/code/local/Mage/Core/Model/Url/Rewrite.php or:
/app/code/local/YourTheme/Mage/Core/Model/Url/Rewrite.php
source:
It looks like a bug in Magento 1.7. Here is a hack that worked for me.
It should work for a two language store with store code in URL
in var/www/html/shop1/app/code/core/Mage/Core/Model/Url/Rewrite.php
remove this line
// $targetUrl = $request->getBaseUrl(). '/' . $this->getRequestPath();
and add these:
$storecode = Mage::app()->getStore()->getCode();
if ($storecode='en')
{
$targetUrl = $request->getBaseUrl(). '/'.$storecode.'/' . $this->getRequestPath();
}
else
{
$targetUrl = $request->getBaseUrl(). '/' . $this->getRequestPath();
}
Here a another solution for this problem. Just add this code after "$this->load($pathInfo, 'request_path');" in app/code/core/Mage/Core/Model/Url/Rewrite.php:
if (!$this->getId() && !isset($_GET['___from_store'])) {
$db = Mage::getSingleton('core/resource')->getConnection('default_read');
$result = $db->query('select store_id from core_url_rewrite WHERE request_path = "' . $pathInfo . '"');
if ($result) {
$storeIds = array();
if($row = $result->fetch(PDO::FETCH_ASSOC)) {
$storeId = $row['store_id'];
$storeCode = Mage::app()->getStore($storeId)->getCode();
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/" . $pathInfo . "?___store=" . $storeCode);
exit();
}
}
}
guys. For this error there is magento module. It have rewrite 2 models
http://www.magentocommerce.com/magento-connect/fix-404-error-in-language-switching.html

Image not showing on IIS when MVC app is hosted on IIS..works on ASP.NET Devlopment server just fine

I have a view which looks like this
{{img src="/Scenario/Status/id" alt="status" /}}
(replace <> these {} above )
and this is the code in action of the controller
public ActionResult Status(int? id)
{
// Calculate the status
int no = new Random().Next(0, 2);
string file = "green.jpg";
if (no == 0)
{
file = "red.jpg";
}
else if (no == 1)
{
file = "yellow.jpg";
}
else if (no == 2)
{
file = "green.jpg";
}
var path = Server.MapPath("/Content/images/");
var filePath = path + file;
return new FileContentResult(System.IO.File.ReadAllBytes(filePath), "image/jpeg");
}
This works just fine when i run on visualstudio. But when i deploy it to local IIS, I dont see these images.
I checked that the "StaticContent" option is checked in Windows Features under IIS and also that the MIME type is enabled on IIS. I also checked that the *.jpg files are present under "inetpub" folder of my app after I publish from visual studio. Since i'm using virtual path for images and not hardcofing the filenames , it should work...
I just tried this
{{img src="../Content/Images/Green.jpg" alt="status" /}} and that works too.. :(
What else could be wrong?
A quick way to gain more insight into the problem would be to set a breakpoint in the Application_Error method of the global.asax, and see what exception is being raised when the request for the image comes in.
If you've deployed under a virtual directory in IIS, You'll need to use Server.MapPath("~/Content/images/")
Where Asp.Net will replace ~ with the application root.
Found the solution for displaying images in an app hosted in a sub folder unde root site on IIS
This worked..
img src = "<%= Url.Content("~/Home/GetRainfallChart") %>" alt="chart"
It is deployed to a virtual directory C:\inetpub\wwwroot\testsite....
Is that th eproblrm

Resources