How to read cookies4.dat file using c#? - c#

I want to display the list of cookies, i am unable to read this file. can anyone please guide me on reading data from this file(cookies4.dat).
It is from opera browser.
Thanks in Advance.

Have you tried the documentation?

This CodeProject article shows details on reading cookies for the major browsers, including Opera. Unfortunately it doesn't give much details on how the magic is done but you should be able to download the code and check it out.
A couple of methods included:
private static string GetOperaCookiePath()
{
string s = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
s += #"\Opera\Opera\cookies4.dat";
if (!File.Exists(s))
return string.Empty;
return s;
}
private static bool GetCookie_Opera(string strHost, string strField, ref string Value)
{
Value = "";
bool fRtn = false;
string strPath;
// Check to see if Opera Installed
strPath = GetOperaCookiePath();
if (string.Empty == strPath) // Nope, perhaps another browser
return false;
try
{
OpraCookieJar cookieJar = new OpraCookieJar(strPath);
List<O4Cookie> cookies = cookieJar.GetCookies(strHost);
if (null != cookies)
{
foreach (O4Cookie cookie in cookies)
{
if (cookie.Name.ToUpper().Equals(strField.ToUpper()))
{
Value = cookie.Value;
fRtn = true;
break;
}
}
}
}
catch (Exception)
{
Value = string.Empty;
fRtn = false;
}
return fRtn;
}

http://www.opera.com/docs/operafiles/#cookies

Related

How to rename file in c# when uploading?

I am developing one application in web api and angularjs. I have file upload part. I am able to upload files and i am not storing files in webroot(i created folder called Uploads). My problem is i am not using any good naming convention to maintain uniqueness of files so there are chances of overriding files. I am new to angularjs so i refered below link. http://instinctcoder.com/angularjs-upload-multiple-files-to-asp-net-web-api/
This is my controller level code.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");
var multipartFormDataStreamProvider = new CustomUploadMultipartFormProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
var fileName = "";
DateTime dt = DateTime.Now;
foreach (var key in multipartFormDataStreamProvider.Contents)
{
var a = key.Headers;
fileName = a.ContentDisposition.FileName;
break;
}
foreach (var key in multipartFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multipartFormDataStreamProvider.FormData.GetValues(key))
{
Console.WriteLine(string.Format("{0}: {1}", key, val));
}
}
In the above code I am trying to add date part to beginning of file name as below
string filenameNew = "App1" + DateTime.Now.ToString("yyyyMMddHHmmss");
fileName = filenameNew + a.ContentDisposition.FileName;
public CustomUploadMultipartFormProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
string startwith = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
return headers
.ContentDisposition
.FileName.TrimEnd('"').TrimStart('"').StartsWith("startwith").ToString();
}
return base.GetLocalFileName(headers);
}
This i tried but whatever the original file name that only comes. May I get some idea where can i append datepart to file while saving? Any help would be appreciated. Thank you.
I'm not sure what you're trying to do inside of the GetLocalFileName, this is pretty messed up.
First off, StartsWith returns a boolean (true or false) that indicates if the string starts with whatever you put in the parenthesis.
string str = "SIMPLE";
bool t = str.StartsWith("SIM"); // true
bool f = str.StartsWith("ZIM"); // false
The fact you're turning this bool back into a string and also passing the string "startsWith" into the method, means it will always return the string "false" (a bool value converted into a string) unless the real filename starts with "startsWith".
I think this is what you're looking for:
public override string GetLocalFileName(HttpContentHeaders headers)
{
string prefix = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
var filename = headers.ContentDisposition.FileName.Trim('"');
return prefix + filename;
}
return base.GetLocalFileName(headers);
}
My suggestion for you is to learn the basics of C# and .Net a bit more, maybe read a C# book or something.

ASP.NET Set cookie ONLY if empty Value

I am trying to set a cookie when the user access my webpage. The value of the cookie is a unique number that I store on my database to keep track of when the user comes back to my website. I set the cookie in my global.asax as follow:
void Application_BeginRequest()
{
string cookievalue = "";
string a = "";
try
{
a = GetCookie();
if (!string.IsNullOrEmpty(a))
{
cookievalue = a;
}
else
{
cookievalue = SetCookie();
}
}
catch (Exception ex)
{
}
}
In BeginRequest() I only want to check if the cookie exist. If exist, then do nothing and keep the value that is already inside the cookie. If it doesn't exist, then set the cookie and add a value.
public static string GetCookie()
{
string cookievalue = "";
try
{
if (HttpContext.Current.Request.Cookies["TestCookie"] != null)
cookievalue = HttpContext.Current.Response.Cookies["TestCookie"].Value;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
public static string SetCookie()
{
string cookievalue = "";
try
{
HttpCookie myCookie = new HttpCookie("TestCookie");
// Set the cookie value.
myCookie.Value = "1234"; //1234 is my unique number
myCookie.Expires = DateTime.Now.AddYears(50);
HttpContext.Current.Response.Cookies.Add(myCookie);
cookievalue = id;
}
catch (Exception ex)
{
//
}
return cookievalue;
}
The problem is that everytime I reload the page, "TestCookie" gets rewritten with a new value. I have been reading the MSDN about how cookies are stored in ASP.NET and according to the instructions, the way it is supposed to work fine. I must be doing something wrong that I cannot see it. I had all this code inside a normal page e.g. test.aspx.cs to test it early but had the same result and decided to move it to the application level and see if that would make any difference but it did not :(.

How to create OneNote 2010 section

How can you create a new section in a OneNote 2010 notebook with c#? According to the API there is no method to do so. But there is a CreateNewPage Method so I wondering if there is something similiar for sections? If not, how can this be achieved except for manipulating the XML files (which is a task i'd like to avoid since I'm not experienced in it)?
Here is code snippet from my add on:
public bool AddNewSection(string SectionTitle, out string newSectionId)
{
try
{
string CurrParentId;
string CurrParentName;
string strPath;
CurrParentId = FindCurrentlyViewedSectionGroup(out CurrParentName);
if (string.IsNullOrWhiteSpace(CurrParentId) || string.IsNullOrWhiteSpace(CurrParentName))
{
CurrParentId = FindCurrentlyViewedNotebook(out CurrParentName);
if (string.IsNullOrWhiteSpace(CurrParentId) || string.IsNullOrWhiteSpace(CurrParentName))
{
newSectionId = string.Empty;
return false;
}
strPath = FindCurrentlyViewedItemPath("Notebook");
}
else
strPath = FindCurrentlyViewedItemPath("SectionGroup");
if (string.IsNullOrWhiteSpace(strPath))
{
newSectionId = string.Empty;
return false;
}
SectionTitle = SectionTitle.Replace(':', '\\');
SectionTitle = SectionTitle.Trim('\\');
strPath += "\\" + SectionTitle + ".one";
onApp.OpenHierarchy(strPath, null, out newSectionId, Microsoft.Office.Interop.OneNote.CreateFileType.cftSection);
onApp.NavigateTo(newSectionId, "", false);
}
catch
{
newSectionId = string.Empty;
return false;
}
return true;
}
Basically what I am doing here is to get the path of currently viewing Section Group or Notebook and then adding new section name to that path and then calling OpenHierarchy method. OpenHierarchy creates a new section with title provided and returns it's id.
Following is where I create a new section and Navigate to it:
onApp.OpenHierarchy(strPath, null, out newSectionId, Microsoft.Office.Interop.OneNote.CreateFileType.cftSection);
onApp.NavigateTo(newSectionId, "", false);
So can write something like:
static void CreateNewSectionMeetingsInWorkNotebook()
{
String strID;
OneNote.Application onApplication = new OneNote.Application();
onApplication.OpenHierarchy("C:\\Documents and Settings\\user\\My Documents\\OneNote Notebooks\\Work\\Meetings.one",
System.String.Empty, out strID, OneNote.CreateFileType.cftSection);
}

Parallel.ForEach Error when using WebClient

First, my disclaimer: I'm a parallel noob. I thought this would be an easy "embarrassingly parallel" problem to tackle, but it's thrown me for a loop.
I'm trying to download some photos in parallel from the web. The original photos are Hi-Res and take up quite a bit of space, so I'm going to compact them once they're downloaded.
Here's the code:
private static void DownloadPhotos(ISet<MyPhoto> photos)
{
List<MyPhoto> failed = new List<MyPhoto>();
DateTime now = DateTime.Now;
string folderDayOfYear = now.DayOfYear.ToString();
string folderYear = now.Year.ToString();
string imagesFolder = string.Format("{0}{1}\\{2}\\", ImagePath, folderYear, folderDayOfYear);
if (!Directory.Exists(imagesFolder))
{
Directory.CreateDirectory(imagesFolder);
}
Parallel.ForEach(photos, photo =>
{
if (!SavePhotoFile(photo.Url, photo.Duid + ".jpg", imagesFolder))
{
failed.Add(photo);
Console.WriteLine("adding to failed photos: {0} ", photo.Duid.ToString());
}
});
Console.WriteLine();
Console.WriteLine("failed photos count: {0}", failed.Count);
RemoveHiResPhotos(string.Format(#"{0}\{1}\{2}", ImagePath, folderYear, folderDayOfYear));
}
private static bool SavePhotoFile(string url, string fileName, string imagesFolder)
{
string fullFileName = imagesFolder + fileName;
string originalFileName = fileName.Replace(".jpg", "-original.jpg");
string fullOriginalFileName = imagesFolder + originalFileName;
if (!File.Exists(fullFileName))
{
using (WebClient webClient = new WebClient())
{
try
{
webClient.DownloadFile(url, fullOriginalFileName);
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine("failed to download photo: {0}", fileName);
return false;
}
}
CreateStandardResImage(fullOriginalFileName, fullOriginalFileName.Replace("-original.jpg", ".jpg"));
}
return true;
}
private static void CreateStandardResImage(string hiResFileName, string stdResFileName)
{
Image image = Image.FromFile(hiResFileName);
Image newImage = image.Resize(1024, 640);
newImage.SaveAs(hiResFileName, stdResFileName, 70, ImageFormat.Jpeg);
}
So here's where things confuse me: each of the photos hits the Catch{} block of the SavePhotoFile() method at the webClient.DownloadFile line. The error message is an exception occured during a WebClient request and the inner detail is "The process cannot access the file . . . -original.jpg because it is being used by another process."
If I wasn't confused enough by this error, I'm confused even more by what happens next. It turns out that if I just ignore the message and wait, the image will eventually download and be processed.
What's going on?
OK, so it appears in my focus on parallelism that I made a simple error: I assumed something about my data that wasn't true. Brianestey figured out the problem: Duid isn't unique. It's supposed to be unique, except for some missing code in the process to create the list.
The fix was to add this to the MyPhoto class
public override bool Equals(object obj)
{
if (obj is MyPhoto)
{
var objPhoto = obj as MyPhoto;
if (objPhoto.Duid == this.Duid)
return true;
}
return false;
}
public override int GetHashCode()
{
return this.Duid.GetHashCode();
}

Get url from firefox 8 not working anymore

I have a windows applicaiton c# catching the url of a running firefox instance.
I have always used "MozillaContentWindow" to get firefox URL but i dont understand why it dont work anymore.
string s = GetUrlFromBrowsersWithIdentifier("MozillaContentWindow", foreGround);
public string GetUrlFromBrowsersWithIdentifier(string identifier, int foreground)
{
try
{
IntPtr ptr = new IntPtr(foreground);
var aeBrowser = AutomationElement.FromHandle(ptr);
return aeBrowser == null ? "" : GetURLfromBrowser(aeBrowser, identifier);
}
catch (Exception ex)
{
return "";
}
}
string GetURLfromBrowser(AutomationElement rootElement, string identifier)
{
try
{
Condition condition1 = new PropertyCondition(AutomationElement.IsContentElementProperty, true);
Condition condition2 = new PropertyCondition(AutomationElement.ClassNameProperty, identifier);
var walker = new TreeWalker(new AndCondition(condition1, condition2));
var elementNode = walker.GetFirstChild(rootElement);
if (elementNode != null)
{
var p = elementNode.GetSupportedPatterns();
if (p.Any(autop => autop.ProgrammaticName.Equals("ValuePatternIdentifiers.Pattern")))
{
var valuePattern = elementNode.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
if (valuePattern != null)
return (valuePattern.Current.Value);
}
}
}
catch
{
return "";
}
return "";
}
Now when it enters "walker.GetFirstChild(rootElement);" it just stops there. I cant figure out why. This only happend on latest version of firefox.
Did they change the name of the value bar containing the url?
Thank you
Try using MozillaWindowContentClass for newer versions.

Categories

Resources