private static ActionResult ConvertStreamToActionResult(ConversionInfo conversionInfo, MemoryStream ms) { ms.Position = 0; var mimeType = conversionInfo.Metadata.MimeType; if (mimeType.StartsWith("text", StringComparison.CurrentCultureIgnoreCase)) { using (ms) { using (var sr = new StreamReader(ms)) { return(new ContentResult { Content = sr.ReadToEnd(), ContentType = mimeType }); } } } else { return(new FileStreamResult(ms, mimeType) { FileDownloadName = string.Format("Joseph Lombrozo's Resume.{0}", conversionInfo.Metadata.Format) }); } }
protected void Page_Load(object sender, EventArgs e) { ci = EditedObject as ConversionInfo; if (ci == null) { RedirectToAccessDenied(GetString("general.invalidparameters")); } if (!ci.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(ci.TypeInfo.ModuleName, "Read"); } // Get the conversions currentValues = GetCampaigns(); if (!RequestHelper.IsPostBack()) { usCampaigns.Value = currentValues; } usCampaigns.WhereCondition = "CampaignSiteID = " + SiteContext.CurrentSiteID; usCampaigns.OnSelectionChanged += usConversions_OnSelectionChanged; }
private ConversionInfo GetConversion(Type sourceType, Type targetType) { lock (conversions) { var key = new ConversionKey(sourceType, targetType); ConversionInfo conversion; if (!conversions.TryGetValue(key, out conversion)) { // Try to get a custom user converter. Conversion operation = extensionPoints.CustomConverters.Find(key); if (operation != null) { var rule = new CustomConversionRule(operation); conversion = new ConversionInfo(ConversionCost.Best, rule); } else { // Note: We add a null info record while populating the cache so as to handle // potentially recursive lookups by preventing them from being satisfied. conversions.Add(key, ConversionInfo.Null); conversion = GetConversionWithoutCache(sourceType, targetType); } conversions[key] = conversion; } return(conversion); } }
/// <inheritdoc /> protected override object ConvertImpl(object sourceValue, Type targetType) { if (sourceValue == null) { return(ConvertNull(targetType)); } bool nullable = ReflectionUtils.IsNullable(targetType); targetType = GetUnderlyingTypeOfNullableIfPresent(targetType); if (targetType.IsInstanceOfType(sourceValue)) { return(sourceValue); } Type sourceType = sourceValue.GetType(); ConversionInfo conversion = GetConversion(sourceType, targetType); if (conversion.Cost.IsInvalid) { throw new InvalidOperationException(String.Format("There is no registered conversion rule to convert a value of type '{0}' to type '{1}'.", sourceType, targetType)); } return(conversion.Rule.Convert(sourceValue, targetType, this, nullable)); }
bool MatchAssignments(Block block, ref int pos, Dictionary <ILVariable, ConversionInfo> conversions, List <StLoc> conversionStLocs, ref Action <DeconstructInstruction> delayedActions) { int previousIndex = -1; int conversionStLocIndex = 0; int startPos = pos; while (MatchAssignment(block.Instructions.ElementAtOrDefault(pos), out var targetType, out var valueInst, out var addAssignment)) { int index = FindIndex(valueInst, out var tupleAccessAdjustment); if (index <= previousIndex) { return(false); } AddMissingAssignmentsForConversions(index, ref delayedActions); if (!(valueInst.MatchLdLoc(out var resultVariable) && conversions.TryGetValue(resultVariable, out var conversionInfo))) { conversionInfo = new ConversionInfo { inputType = valueInst.InferType(context.TypeSystem) }; } if (block.Instructions[pos].MatchStLoc(out var assignmentTarget, out _) && assignmentTarget.Kind == VariableKind.StackSlot && assignmentTarget.IsSingleDefinition && conversionInfo.conv == null) { delayedActions += _ => { assignmentTarget.Type = conversionInfo.inputType; }; }
protected void Page_Load(object sender, EventArgs e) { lblAvialable.Text = GetString("conversion.avaiblecampaign"); conversionID = QueryHelper.GetInteger("campaignid", 0); ConversionInfo ci = ConversionInfoProvider.GetConversionInfo(conversionID); if (ci != null) { int siteID = CMSContext.CurrentSiteID; if (ci.ConversionSiteID != siteID) { if (!CMSContext.CurrentUser.IsInSite(SiteInfoProvider.GetSiteName(ci.ConversionSiteID))) { RedirectToAccessDenied(GetString("conversion.currentsite")); return; } } } // Get the conversions currentValues = GetConversions(); if (!RequestHelper.IsPostBack()) { usCampaigns.Value = currentValues; } usCampaigns.WhereCondition = "CampaignSiteID = " + CMSContext.CurrentSiteID; usCampaigns.OnSelectionChanged += usConversions_OnSelectionChanged; }
protected override void OnPreInit(EventArgs e) { // Checks all permissions for web analytics CMSWebAnalyticsPage.CheckAllPermissions(); string conversionName = QueryHelper.GetString("conversionName", String.Empty); int conversionID = QueryHelper.GetInteger("conversionID", 0); ConversionInfo ci = null; if (conversionName != String.Empty) { // Try to check dialog mode conversionName = conversionName.Trim(';'); ci = ConversionInfoProvider.GetConversionInfo(conversionName, CMSContext.CurrentSiteName); } if (conversionID != 0) { ci = ConversionInfoProvider.GetConversionInfo(conversionID); } if ((conversionName != String.Empty) && (ci == null)) { // Set warning text infoText = String.Format(GetString("conversion.editedobjectnotexits"), conversionName); // Create new conversion info based on conversion name ci = new ConversionInfo(); ci.ConversionName = conversionName; ci.ConversionDisplayName = conversionName; } modalDialog = QueryHelper.GetBoolean("modalDialog", false); if (modalDialog) { MasterPageFile = "~/CMSMasterPages/UI/Dialogs/ModalDialogPage.master"; if (ci != null) { this.CurrentMaster.Title.TitleText = GetString("analytics.conversion"); this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Analytics_Conversion/object.png"); } else { this.CurrentMaster.Title.TitleText = GetString("conversion.conversion.new"); this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Analytics_Conversion/new.png"); } SetDialogButtons(); } if (ci != null) { EditedObject = ci; } base.OnPreInit(e); }
void EditForm_OnAfterSave(object sender, EventArgs e) { ConversionInfo ci = EditForm.EditedObject as ConversionInfo; // If code name has changed (on existing object) => Rename all analytics statistics data. if ((ci != null) && (ci.ConversionName != oldConversionName) && (oldConversionName != String.Empty)) { ConversionInfoProvider.RenameConversionStatistics(oldConversionName, ci.ConversionName, CMSContext.CurrentSiteID); } }
void EditForm_OnBeforeSave(object sender, EventArgs e) { ConversionInfo ci = EditForm.EditedObject as ConversionInfo; if (ci != null) { ci.ConversionSiteID = CMSContext.CurrentSiteID; oldConversionName = ci.ConversionName; } }
void AddConversionUpdate(ConversionInfo conversionInfo) { ListViewItem newItem = new ListViewItem(); newItem.Text = Path.GetFileName(conversionInfo.SourcePath); newItem.SubItems.Add(Path.GetFileName(conversionInfo.DestinationPath)); newItem.SubItems.Add(conversionInfo.Page > 0 ? conversionInfo.Page.ToString() : "NA"); newItem.SubItems.Add(conversionInfo.Result.ToString()); _lvResults.Items.Add(newItem); Application.DoEvents(); }
protected void Page_Init(object sender, EventArgs e) { var ci = EditedObject as ConversionInfo; var conversionName = QueryHelper.GetString("conversionName", String.Empty); if (conversionName != String.Empty) { // Try to check dialog mode conversionName = conversionName.Trim(';'); ci = ConversionInfoProvider.GetConversionInfo(conversionName, SiteContext.CurrentSiteName); } // Test whether conversion is in current site, if not - test if user is authorized for conversion's site if (ci != null) { if (!ci.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(ci.TypeInfo.ModuleName, "Read"); } } if ((conversionName != String.Empty) && (ci == null)) { // Set warning text mInfoText = String.Format(GetString("conversion.editedobjectnotexits"), HTMLHelper.HTMLEncode(conversionName)); // Create new conversion info based on conversion name ci = new ConversionInfo(); ci.ConversionName = conversionName; ci.ConversionDisplayName = conversionName; } if (mModalDialog) { if (ci != null) { PageTitle.TitleText = GetString("analytics.conversion"); } else { PageTitle.TitleText = GetString("conversion.conversion.new"); } } if (ci != null) { EditedObject = ci; } }
/// <inheritdoc /> protected override ConversionCost GetConversionCostImpl(Type sourceType, Type targetType) { sourceType = GetUnderlyingTypeOfNullableIfPresent(sourceType); targetType = GetUnderlyingTypeOfNullableIfPresent(targetType); if (sourceType.Equals(targetType)) { return(ConversionCost.Zero); } ConversionInfo conversion = GetConversion(sourceType, targetType); return(conversion.Cost); }
/// <summary> /// Test if conversion is valid and create new conversion if not exists /// </summary> public override bool IsValid() { // Get validated string String value = ValidationHelper.GetString(usConversions.Value, String.Empty).Trim(); if (value != String.Empty) { String domain = RequestContext.CurrentDomain; if (DataHelper.GetNotEmpty(domain, "") != "") { string parsedDomain = LicenseKeyInfoProvider.ParseDomainName(domain); if (!LicenseKeyInfoProvider.IsFeatureAvailable(parsedDomain, FeatureEnum.CampaignAndConversions)) { ValidationError = GetString("conversionselector.nolicence"); return(false); } } // Validate for code name if (!ValidationHelper.IsCodeName(value)) { ValidationError = GetString("conversion.validcodename"); return(false); } // Test if selected name exists ConversionInfo ci = ConversionInfoProvider.GetConversionInfo(value, SiteContext.CurrentSiteName); // If not exist create new one if (ci == null) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.WebAnalytics", "ManageConversions")) { ValidationError = GetString("conversion.notallowedcreate"); return(false); } // Create new object ci = new ConversionInfo(); ci.ConversionName = value; ci.ConversionDisplayName = value; ci.ConversionSiteID = SiteContext.CurrentSiteID; // Save to database ConversionInfoProvider.SetConversionInfo(ci); } } return(true); }
protected void Page_Init(object sender, EventArgs e) { ConversionInfo ci = EditedObject as ConversionInfo; string conversionName = QueryHelper.GetString("conversionName", String.Empty); if (conversionName != String.Empty) { // Try to check dialog mode conversionName = conversionName.Trim(';'); ci = ConversionInfoProvider.GetConversionInfo(conversionName, SiteContext.CurrentSiteName); } // Test whether conversion is in current site, if not - test if user is authorized for conversion's site if (ci != null) { if (!ci.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(ci.TypeInfo.ModuleName, "Read"); } } if ((conversionName != String.Empty) && (ci == null)) { // Set warning text infoText = String.Format(GetString("conversion.editedobjectnotexits"), HTMLHelper.HTMLEncode(conversionName)); // Create new conversion info based on conversion name ci = new ConversionInfo(); ci.ConversionName = conversionName; ci.ConversionDisplayName = conversionName; } if (modalDialog) { if (ci != null) { PageTitle.TitleText = GetString("analytics.conversion"); } else { PageTitle.TitleText = GetString("conversion.conversion.new"); } } if (ci != null) { EditedObject = ci; } }
private ConversionInfo GetConversionWithoutCache(Type sourceType, Type targetType) { ConversionInfo best = ConversionInfo.Null; foreach (IConversionRule rule in rules) { ConversionCost cost = rule.GetConversionCost(sourceType, targetType, this); if (cost.CompareTo(best.Cost) < 0 && !cost.IsInvalid) { best = new ConversionInfo(cost, rule); } } return(best); }
private static void ConvertResumeToStream(ConversionInfo conversionInfo, MemoryStream ms) { if (conversionInfo.Converter is IResumeConverter) { var conv = (IResumeConverter)conversionInfo.Converter; conv.WriteToStream(GetResume(), ms); } else if (conversionInfo.Converter is IXmlResumeConverter) { var conv = (IXmlResumeConverter)conversionInfo.Converter; conv.WriteToStream(GetXmlDocument(), ms); } }
public IHttpActionResult Index(ConversionRequest model) { var request = new ConversionInfo { Amount = model.Amount, Name = model.Name }; var result = _amountToTextService.Convert(request); if (result == null) { // or internal server ? return(BadRequest()); } else { return(Ok(result)); } }
/// <summary> /// Saves the data /// </summary> /// <param name="redirect">If true, use server redirect after successfull save</param> public bool Save(bool redirect) { string selectorID = QueryHelper.GetString("selectorID", String.Empty); bool ret = EditForm.SaveData(""); // If saved - redirect with ConversionID parameter if ((ret) && (redirect)) { ConversionInfo ci = (ConversionInfo)EditForm.EditedObject; if (ci != null) { URLHelper.Redirect("edit.aspx?conversionid=" + ci.ConversionID + "&saved=1&modaldialog=true&selectorID=" + selectorID); } } return(ret); }
/// <summary> /// Adds scripts to update parent's uniselector (used in modal dialogs) /// </summary> /// <param name="closeOnSave">If true, window close JS is added</param> private void UpdateUniSelector(bool closeOnSave) { string selector = QueryHelper.GetString("selectorid", string.Empty); ConversionInfo info = editElem.UIFormControl.EditedObject as ConversionInfo; if (!string.IsNullOrEmpty(selector) && (info != null)) { // Add selector refresh string script = string.Format(@"var wopener = window.top.opener ? window.top.opener : window.top.dialogArguments; if (wopener) {{ wopener.US_SelectNewValue_{0}('{1}'); }}" , selector, info.ConversionName); if (closeOnSave) { script += "window.top.close();"; } ScriptHelper.RegisterStartupScript(this, GetType(), "UpdateSelector", script, true); } }
bool MatchConversion(ILInstruction inst, out ILInstruction inputInstruction, out ILVariable outputVariable, out ConversionInfo info) { info = default; inputInstruction = null; if (!inst.MatchStLoc(out outputVariable, out var value)) { return(false); } if (!(value is Conv conv)) { return(false); } info = new ConversionInfo { inputType = conv.Argument.InferType(context.TypeSystem), conv = conv }; inputInstruction = conv.Argument; return(true); }
/// <summary> /// Adds scripts to update parent's uniselector (used in modal dialogs) /// </summary> /// <param name="closeOnSave">If true, window close JS is added</param> private void UpdateUniSelector(bool closeOnSave) { string selector = HTMLHelper.HTMLEncode(QueryHelper.GetString("selectorid", string.Empty)); ConversionInfo info = editElem.UIFormControl.EditedObject as ConversionInfo; if (!string.IsNullOrEmpty(selector) && (info != null)) { ScriptHelper.RegisterWOpenerScript(this); // Add selector refresh string script = string.Format(@"if (wopener) {{ wopener.US_SelectNewValue_{0}('{1}'); }}", selector, info.ConversionName); if (closeOnSave) { script += "CloseDialog();"; } ScriptHelper.RegisterStartupScript(this, GetType(), "UpdateSelector", script, true); } }
// Do conversion during extraction. public static IFormat DoExtractionConversion(ConversionInfo c, BinaryReader r, long fileOff, string originalFilePath, byte[] file, bool parentWasLZ = false) { IFormat newData = null; foreach (var pFormat in Helper.FileFormats) { newData = (IFormat)Activator.CreateInstance(pFormat); if (newData.IsType(file)) { if (newData as LZFile != null && parentWasLZ) { continue; // No double LZ compression. } if (newData as Enpg != null && !originalFilePath.EndsWith(".enpg")) { continue; // Only assume valid Enpgs are ones that have the extension. } if (newData as Narc != null) { Narc.ConversionInfo = c; // Must do this to allow conversion. } r.BaseStream.Position = fileOff; newData.Read(r, file); byte[] containedFile = newData.ContainedFile(); c.AddFileConversion(originalFilePath, newData.GetFormat(), newData); if (containedFile != null) { using (MemoryStream src = new MemoryStream(containedFile)) { BinaryReader br = new BinaryReader(src); DoExtractionConversion(c, br, 0, originalFilePath, containedFile, newData as LZFile != null); } } break; } } return(newData); }
/// <summary> /// Displays the given report /// </summary> private void DisplayReport() { // If report was already displayed .. return if (reportDisplayed) { return; } ucGraphType.ProcessChartSelectors(false); // Prepare report parameters DataTable reportParameters = new DataTable(); // In case of hidden datetime -> for save purpose pass from (to) as now to query parameter DateTime from = ((ucGraphType.From == DateTimeHelper.ZERO_TIME) && !pnlHeader.Visible) ? DateTime.Now : ucGraphType.From; DateTime to = ((ucGraphType.To == DateTimeHelper.ZERO_TIME) && !pnlHeader.Visible) ? DateTime.Now : ucGraphType.To; reportParameters.Columns.Add("FromDate", typeof(DateTime)); reportParameters.Columns.Add("ToDate", typeof(DateTime)); reportParameters.Columns.Add("CodeName", typeof(string)); reportParameters.Columns.Add("CampaignName", typeof(string)); reportParameters.Columns.Add("ConversionName", typeof(string)); reportParameters.Columns.Add("Goal", typeof(string)); reportParameters.Columns.Add("SiteID", typeof(int)); object[] parameters = new object[7]; parameters[0] = (mAllowNoTimeSelection && from == DateTimeHelper.ZERO_TIME) ? (DateTime?)null : from; parameters[1] = (mAllowNoTimeSelection && to == DateTimeHelper.ZERO_TIME) ? (DateTime?)null : to; parameters[2] = dataCodeName; parameters[3] = String.Empty; parameters[4] = String.Empty; parameters[5] = ucReportHeader.SelectedGoal; parameters[6] = ucReportHeader.SelectedSiteID; // Get report name from query String reportName = ucGraphType.GetReportName(reportCodeNames); // Filter campaign if any campaign selected string campaignName = ValidationHelper.GetString(ucReportHeader.SelectedCampaign, String.Empty); if ((campaignName != ucReportHeader.AllRecordValue) && (!String.IsNullOrEmpty(campaignName))) { parameters[3] = campaignName; } if (conversionID == 0) { // Filter conversion String conversionName = ValidationHelper.GetString(ucReportHeader.SelectedConversion, String.Empty); if ((conversionName != ucReportHeader.AllRecordValue) && (!String.IsNullOrEmpty(conversionName))) { parameters[4] = conversionName; } } else { ConversionInfo ci = ConversionInfoProvider.GetConversionInfo(conversionID); if (ci != null) { parameters[4] = ci.ConversionName; mDeleteParam = "singleconversion;" + ci.ConversionName; } } reportParameters.Rows.Add(parameters); reportParameters.AcceptChanges(); mUcDisplayReport.ReportName = reportName; // Set display report if (!mUcDisplayReport.IsReportLoaded()) { ShowError(String.Format(GetString("Analytics_Report.ReportDoesnotExist"), HTMLHelper.HTMLEncode(reportName))); } else { mUcDisplayReport.LoadFormParameters = false; mUcDisplayReport.DisplayFilter = false; mUcDisplayReport.ReportParameters = reportParameters.Rows[0]; mUcDisplayReport.GraphImageWidth = 100; mUcDisplayReport.IgnoreWasInit = true; mUcDisplayReport.UseExternalReload = true; mUcDisplayReport.UseProgressIndicator = true; mUcDisplayReport.SelectedInterval = HitsIntervalEnumFunctions.HitsConversionToString(ucGraphType.SelectedInterval); mUcDisplayReport.ReloadData(true); } // Mark as report displayed reportDisplayed = true; }
protected void Run() { int encodingScore = 0; if (mbFindTargetEncoding) { List <ConversionInfo> results; if (Directory.Exists(mIn)) { EncodingInfo sourceEncodingInfo = null; foreach (EncodingInfo ei in Encoding.GetEncodings()) { if (ei.CodePage == mSourceEncoding.CodePage) { sourceEncodingInfo = ei; break; } } results = new List <ConversionInfo>(); foreach (EncodingInfo targetEncodingInfo in Encoding.GetEncodings()) { mTargetEncoding = targetEncodingInfo.GetEncoding(); int newScore = 0; ActOnCorruptFilenames(mIn, true, fi => newScore += fi.Name.ReEncode(mSourceEncoding, mTargetEncoding).JapaneseScore(), di => newScore += di.Name.ReEncode(mSourceEncoding, mTargetEncoding).JapaneseScore()); if (newScore != 0) { results.Add(new ConversionInfo(sourceEncodingInfo, targetEncodingInfo, newScore)); } } } else { string seed = mIn; if (File.Exists(mIn)) { seed = Path.GetFileNameWithoutExtension(mIn); } results = FindMostLikelyConversions(seed); } ConversionInfo best = results.OrderBy(x => x.mScore).Last(); mSourceEncoding = best.mOriginal.GetEncoding(); mTargetEncoding = best.mTarget.GetEncoding(); encodingScore = best.mScore; } if (mbRecode) { if (File.Exists(mIn)) { recodeFile(mIn); } else { mError = true; } } else if (mbAllSourceEncodings) { IterateAllSourceEncodings(); } else if (mOut == null) { if (Directory.Exists(mIn)) { ActOnCorruptFilenames(mIn, true, fi => fi.Rename(fi.Name.ReEncode(mSourceEncoding, mTargetEncoding)), di => di.Rename(di.Name.ReEncode(mSourceEncoding, mTargetEncoding))); } else if (File.Exists(mIn)) { if (mIn.EndsWith(".zip", true, CultureInfo.CurrentCulture)) { extractSjisZip(mIn); } else { FileInfo fileInfo = new FileInfo(mIn); fileInfo.Rename(fileInfo.Name.ReEncode(mSourceEncoding, mTargetEncoding)); } } else { mError = true; } } else if (File.Exists(mIn) && mIn.EndsWith(".zip", true, CultureInfo.CurrentCulture)) { var folderPath = Path.GetDirectoryName(mIn); var newFolderPath = Path.Combine(folderPath, mOut); Directory.CreateDirectory(newFolderPath); extractSjisZip(mIn, newFolderPath); } else { mError = true; } String.Format("Converted using {0} ({1}) => {2} ({3})", mSourceEncoding.HeaderName, mSourceEncoding.CodePage, mTargetEncoding.HeaderName, mTargetEncoding.CodePage).wl(); String.Format("({0} => {1})", mSourceEncoding.EncodingName, mTargetEncoding.EncodingName).wl(); if (mbFindTargetEncoding) { String.Format("(score: {0})", encodingScore).wl(); } }
/// <summary> /// 尝试获取指定对象类型的转换器。 /// </summary> /// <param name="type">对象属性类型类型。</param> /// <param name="conversion">转换器。</param> /// <returns>是否成功获取。</returns> internal bool TryGetConversion(Type type, out ConversionInfo conversion) { return(typeConversion.TryGetValue(type, out conversion)); }
/// <summary> /// 注册全局类型转换器。 /// </summary> /// <param name="conversion">转换器类型。</param> public void Register(Type conversion) { var info = new ConversionInfo(conversion); typeConversion.AddOrUpdate(info.ObjectType, info); }
/// <summary> /// Test if conversion is valid and create new conversion if not exists /// </summary> public override bool IsValid() { String value = ValidationHelper.GetString(usConversions.Value, String.Empty).Trim(); if (value != String.Empty) { if (!ValidationHelper.IsCodeName(value)) { this.ValidationError = GetString("conversion.validcodename"); return false; } // Test if selected name exists ConversionInfo ci = ConversionInfoProvider.GetConversionInfo(value, CMSContext.CurrentSiteName); // If not exist create new one if (ci == null) { if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.WebAnalytics", "ManageConversions")) { this.ValidationError = GetString("conversion.notallowedcreate"); return false; } ci = new ConversionInfo(); ci.ConversionName = value; ci.ConversionDisplayName = value; ci.ConversionSiteID = CMSContext.CurrentSiteID; ConversionInfoProvider.SetConversionInfo(ci); } } return true; }
protected override void OnPreInit(EventArgs e) { // Licence for CaC if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), "") != "") { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.CampaignAndConversions); } // Checks all permissions for web analytics CMSWebAnalyticsPage.CheckAllPermissions(); string conversionName = QueryHelper.GetString("conversionName", String.Empty); int conversionID = QueryHelper.GetInteger("conversionID", 0); ConversionInfo ci = null; if (conversionName != String.Empty) { // Try to check dialog mode conversionName = conversionName.Trim(';'); ci = ConversionInfoProvider.GetConversionInfo(conversionName, CMSContext.CurrentSiteName); } if (conversionID != 0) { ci = ConversionInfoProvider.GetConversionInfo(conversionID); } // Test whether conversion is in current site, if not - test if user is authorized for conversion's site if (ci != null) { int siteID = CMSContext.CurrentSiteID; if (ci.ConversionSiteID != siteID) { if (!CMSContext.CurrentUser.IsInSite(SiteInfoProvider.GetSiteName(ci.ConversionSiteID))) { RedirectToAccessDenied(GetString("conversion.currentsite")); return; } } } if ((conversionName != String.Empty) && (ci == null)) { // Set warning text infoText = String.Format(GetString("conversion.editedobjectnotexits"), conversionName); // Create new conversion info based on conversion name ci = new ConversionInfo(); ci.ConversionName = conversionName; ci.ConversionDisplayName = conversionName; } modalDialog = QueryHelper.GetBoolean("modalDialog", false); if (modalDialog) { MasterPageFile = "~/CMSMasterPages/UI/Dialogs/ModalDialogPage.master"; if (ci != null) { CurrentMaster.Title.TitleText = GetString("analytics.conversion"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Analytics_Conversion/object.png"); } else { CurrentMaster.Title.TitleText = GetString("conversion.conversion.new"); CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Analytics_Conversion/new.png"); } SetDialogButtons(); } if (ci != null) { EditedObject = ci; } // Must be called after the master page file is set base.OnPreInit(e); }
private void Add(Type type) { PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo pinfo in properties) { var arr = (UnitAttribute[]) pinfo.GetCustomAttributes(typeof (UnitAttribute), false); foreach (UnitAttribute ua in arr) { string key = MakeKey(type, ua.UnitSymbol); var val = new ConversionInfo {PropInfo = pinfo, UnitInfo = ua}; _Map[key] = val; } } }
private void _btnStart_Click(object sender, EventArgs e) { bool sourceHasAnnFiles = false; try { //check if source exist. if (!Directory.Exists(_txtSourceDirectory.Text)) { MessageBox.Show("The source directory is not existing", "Incorrect source directory", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //check if destination exist. if (!Directory.Exists(_txtDestinationDirectory.Text)) { Directory.CreateDirectory(_txtDestinationDirectory.Text); } } catch (Exception ex) { MessageBox.Show(ex.Message); } _converting = true; _lvResults.Items.Clear(); UpdateButtons(); int index = 0; string[] srcFolderFiles = Directory.GetFiles(_txtSourceDirectory.Text, "*.*", SearchOption.TopDirectoryOnly); foreach (string srcAnnotationFile in srcFolderFiles.Where(ext => ext.ToLower().EndsWith(".ann") || ext.ToLower().EndsWith(".xml") || ext.ToLower().EndsWith(".tif") || ext.ToLower().EndsWith(".pdf"))) { Application.DoEvents(); ConversionInfo conversionInfo = new ConversionInfo(); conversionInfo.SourcePath = srcAnnotationFile; string destAnnotationFile = string.Format("{0}.xml", Path.Combine(_txtDestinationDirectory.Text, Path.GetFileNameWithoutExtension(srcAnnotationFile))); conversionInfo.DestinationPath = destAnnotationFile; try { AnnContainer[] containers = null; double dpiX = 96.0; double dpiY = 96.0; //try to get the relative image for this annotations file assuming it is located behind the annotations file , if it is not exist then take the default dpi 96*96 string relativeImageFile = string.Empty; string fileExt = Path.GetExtension(srcAnnotationFile); if (fileExt.ToLower() == ".tif" || fileExt.ToLower() == ".pdf") { //the annotations is embedded inside the file relativeImageFile = srcAnnotationFile; } else { foreach (string file in srcFolderFiles) { if (Path.GetFileNameWithoutExtension(file) == Path.GetFileNameWithoutExtension(srcAnnotationFile) && Path.GetExtension(file).ToLower() != ".xml" && Path.GetExtension(file).ToLower() != ".ann") { relativeImageFile = file; } } } try { if (relativeImageFile != string.Empty) { using (RasterCodecs codecs = new RasterCodecs()) { CodecsImageInfo imageInfo = codecs.GetInformation(relativeImageFile, false); dpiX = imageInfo.XResolution; dpiY = imageInfo.YResolution; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } AnnCodecs annCodecs = new AnnCodecs(); containers = annCodecs.LoadAll(srcAnnotationFile, dpiX, dpiY); conversionInfo.Result = ConversionResult.Success; using (Stream stream = File.OpenWrite(destAnnotationFile)) { annCodecs.SaveAll(stream, containers, AnnFormat.Annotations); } conversionInfo.Page = index + 1; index++; AddConversionUpdate(conversionInfo); sourceHasAnnFiles = true; } catch (Exception) { conversionInfo.Result = ConversionResult.Failed; AddConversionUpdate(conversionInfo); continue; } } _converting = false; UpdateButtons(); if (sourceHasAnnFiles) { MessageBox.Show("Conversion Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show("There is no valid annotation file in source directory", "No source annotations", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
/// <summary> /// Test if conversion is valid and create new conversion if not exists /// </summary> public override bool IsValid() { String value = ValidationHelper.GetString(usConversions.Value, String.Empty).Trim(); if (value != String.Empty) { String domain = URLHelper.GetCurrentDomain(); if (DataHelper.GetNotEmpty(domain, "") != "") { string parsedDomain = LicenseKeyInfoProvider.ParseDomainName(domain); if (!LicenseKeyInfoProvider.IsFeatureAvailable(parsedDomain, FeatureEnum.CampaignAndConversions)) { ValidationError = GetString("conversionselector.nolicence"); return false; } } if (!ValidationHelper.IsCodeName(value)) { this.ValidationError = GetString("conversion.validcodename"); return false; } // Test if selected name exists ConversionInfo ci = ConversionInfoProvider.GetConversionInfo(value, CMSContext.CurrentSiteName); // If not exist create new one if (ci == null) { if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.WebAnalytics", "ManageConversions")) { this.ValidationError = GetString("conversion.notallowedcreate"); return false; } ci = new ConversionInfo(); ci.ConversionName = value; ci.ConversionDisplayName = value; ci.ConversionSiteID = CMSContext.CurrentSiteID; ConversionInfoProvider.SetConversionInfo(ci); } } return true; }
private ConversionInfo GetConversion(Type sourceType, Type targetType) { lock (conversions) { var key = new ConversionKey(sourceType, targetType); ConversionInfo conversion; if (!conversions.TryGetValue(key, out conversion)) { // Try to get a custom user converter. Conversion operation = extensionPoints.CustomConverters.Find(key); if (operation != null) { var rule = new CustomConversionRule(operation); conversion = new ConversionInfo(ConversionCost.Best, rule); } else { // Note: We add a null info record while populating the cache so as to handle // potentially recursive lookups by preventing them from being satisfied. conversions.Add(key, ConversionInfo.Null); conversion = GetConversionWithoutCache(sourceType, targetType); } conversions[key] = conversion; } return conversion; } }
private static ActionResult ConvertStreamToActionResult(ConversionInfo conversionInfo, MemoryStream ms) { ms.Position = 0; var mimeType = conversionInfo.Metadata.MimeType; if (mimeType.StartsWith("text", StringComparison.CurrentCultureIgnoreCase)) { using (ms) { using (var sr = new StreamReader(ms)) { return new ContentResult { Content = sr.ReadToEnd(), ContentType = mimeType }; } } } else { return new FileStreamResult(ms, mimeType) { FileDownloadName = string.Format("Joseph Lombrozo's Resume.{0}", conversionInfo.Metadata.Format) }; } }
protected override void OnPreInit(EventArgs e) { // Checks all permissions for web analytics CMSWebAnalyticsPage.CheckAllPermissions(); string conversionName = QueryHelper.GetString("conversionName", String.Empty); int conversionID = QueryHelper.GetInteger("conversionID", 0); ConversionInfo ci = null; if (conversionName != String.Empty) { // Try to check dialog mode conversionName = conversionName.Trim(';'); ci = ConversionInfoProvider.GetConversionInfo(conversionName, CMSContext.CurrentSiteName); } if (conversionID != 0) { ci = ConversionInfoProvider.GetConversionInfo(conversionID); } // Test whether conversion is in current site, if not - test if user is authorized for conversion's site if (ci != null) { int siteID = CMSContext.CurrentSiteID; if (ci.ConversionSiteID != siteID) { if (!CMSContext.CurrentUser.IsInSite(SiteInfoProvider.GetSiteName(ci.ConversionSiteID))) { RedirectToAccessDenied(GetString("conversion.currentsite")); return; } } } if ((conversionName != String.Empty) && (ci == null)) { // Set warning text infoText = String.Format(GetString("conversion.editedobjectnotexits"), conversionName); // Create new conversion info based on conversion name ci = new ConversionInfo(); ci.ConversionName = conversionName; ci.ConversionDisplayName = conversionName; } modalDialog = QueryHelper.GetBoolean("modalDialog", false); if (modalDialog) { MasterPageFile = "~/CMSMasterPages/UI/Dialogs/ModalDialogPage.master"; if (ci != null) { this.CurrentMaster.Title.TitleText = GetString("analytics.conversion"); this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Analytics_Conversion/object.png"); } else { this.CurrentMaster.Title.TitleText = GetString("conversion.conversion.new"); this.CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Analytics_Conversion/new.png"); } SetDialogButtons(); } if (ci != null) { EditedObject = ci; } base.OnPreInit(e); }
private ConversionInfo GetConversionWithoutCache(Type sourceType, Type targetType) { ConversionInfo best = ConversionInfo.Null; foreach (IConversionRule rule in rules) { ConversionCost cost = rule.GetConversionCost(sourceType, targetType, this); if (cost.CompareTo(best.Cost) < 0 && ! cost.IsInvalid) best = new ConversionInfo(cost, rule); } return best; }