Delete CustomXml files -docx4j - docx4j

How to delete custom XML files with its property and relationship files?, I've used clear() method. But it's not working. Help me out.
wordMLPackage.getCustomXmlDataStorageParts().clear();

https://github.com/plutext/docx4j/blob/master/docx4j-core/src/main/java/org/docx4j/Docx4J.java#L643 shows you how to do this. To remove them all, it would be:
protected static void removeDefinedCustomXmlParts(WordprocessingMLPackage wmlPackage) {
List<PartName> partsToRemove = new ArrayList<PartName>();
RelationshipsPart relationshipsPart = wmlPackage.getMainDocumentPart().getRelationshipsPart();
List<Relationship> relationshipsList = ((relationshipsPart != null) &&
(relationshipsPart.getRelationships() != null) ?
relationshipsPart.getRelationships().getRelationship() : null);
Part part = null;
if (relationshipsList != null) {
for (Relationship relationship : relationshipsList) {
if (Namespaces.CUSTOM_XML_DATA_STORAGE.equals(relationship.getType())) {
part = relationshipsPart.getPart(relationship);
partsToRemove.add(part.getPartName());
}
}
}
if (!partsToRemove.isEmpty()) {
for (int i=0; i<partsToRemove.size(); i++) {
relationshipsPart.removePart(partsToRemove.get(i));
}
}
}

Related

CS0103 This name '' does not exist in the current context

I've got this class:
public override void Process(TagHelperContext context,
TagHelperOutput output)
{
if (ViewContext != null && PageModel != null)
{
IUrlHelper urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
TagBuilder result = new TagBuilder("div");
for (int i = 1; i <= PageModel.TotalPages; i++)
{
TagBuilder tag = new TagBuilder("a");
tag.Attributes["href"] = urlHelper.Action(PageAction,
new { productPage = i });
}
tag.InnerHtml.Append(i.ToString());
result.InnerHtml.AppendHtml(tag);
}
output.Content.AppendHtml(result.InnerHtml);
}
However, the 'tag', 'i' and 'result' attributes after the for-loop don't fall in the scope, which shouldn't be the matter if I'm correct. I'm using VS2022 with SDK version 6.0.402.
I'm not sure what you want in the end, but one thing you should pay attention to is that variables defined in a for loop can only be used in a for loop, and variables defined in an if can only be used in an if.
So tag.InnerHtml.Append(i.ToString()); can only be used in a for loop, unless you define an i outside the for loop. Like this:
int k = 0;
for (int i = 1; i <= PageModel.TotalPages; i++)
{
k=i;//The final value of k is PageModel.TotalPages.Count
}
tag.InnerHtml.Append(k.ToString());
If you want to add all i in TagBuilder tag, then it should be like this:
public override void Process(TagHelperContext context,
TagHelperOutput output)
{
TagBuilder result = new TagBuilder("div");
if (ViewContext != null && PageModel != null)
{
IUrlHelper urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
TagBuilder tag = new TagBuilder("a");
for (int i = 1; i <= PageModel.TotalPages; i++)
{
tag.Attributes["href"] = urlHelper.Action(PageAction,
new { productPage = i });
tag.InnerHtml.Append(i.ToString());
}
result.InnerHtml.AppendHtml(tag);
}
output.Content.AppendHtml(result.InnerHtml);
}
If you only want to add the last entry of PageModel.TotalPages in the TagBuilder tag, it should be like this:
public override void Process(TagHelperContext context,
TagHelperOutput output)
{
TagBuilder result = new TagBuilder("div");
if (ViewContext != null && PageModel != null)
{
IUrlHelper urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext);
TagBuilder tag = new TagBuilder("a");
for (int i = 1; i <= PageModel.TotalPages; i++)
{
tag = new TagBuilder("a");
tag.Attributes["href"] = urlHelper.Action(PageAction,
new { productPage = i });
tag.InnerHtml.Append(i.ToString());
}
result.InnerHtml.AppendHtml(tag);
}
output.Content.AppendHtml(result.InnerHtml);
}
Hope this can help you.

Swashbuckle Swagger - Pulling information from Attributes and putting it into the Schema definition

I am trying to have pull the DisplayAttribute and the DescriptionAttribute from parts of the Swagger Model. For example I may have a Body Parameter which has properties with attributes, which I would also want to be generated in the swagger.json and visible in SwaggerUI.
So far I think the approach that should work would be using a custom filter with swashbuckle. I got a proof of concept using the IParameterFilter which displays the description attribute, not sure if another filter would be better.
Issues:
Finding the key for the schemaRegistry fails for some types, like list.
Need to get the key for the parameter to be generated the same as swagger.
Might need recursion to loop through child properties that contain complex objects.
public class SwaggerParameterFilter : IParameterFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
public SwaggerParameterFilter(SchemaRegistrySettings settings = null)
{
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
try
{
if (context.ApiParameterDescription?.ModelMetadata?.Properties == null) return;
if (parameter is BodyParameter bodyParameter)
{
string idFor = _schemaIdManager.IdFor(context.ApiParameterDescription.Type);
var schemaRegistry = (SchemaRegistry)context.SchemaRegistry;
//not perfect, crashes with some cases
var schema = schemaRegistry.Definitions[idFor];
//bodyParameter.Schema, this doesn't seem right, no properties
foreach (var modelMetadata in context.ApiParameterDescription.ModelMetadata.Properties)
{
if (modelMetadata is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name))
{
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute)x);
var descriptionAttribute = (DescriptionAttribute)attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
}
}
}
}
}
catch (Exception e)
{
//eat because above is broken
}
}
}
Edit add looping.
public class SwaggerParameterFilter : IParameterFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
public SwaggerParameterFilter(SchemaRegistrySettings settings = null)
{
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
try
{
if (context.ApiParameterDescription?.ModelMetadata?.Properties == null) return;
//Only BodyParameters are complex and stored in the schema
if (parameter is BodyParameter bodyParameter)
{
var idFor = _schemaIdManager.IdFor(context.ApiParameterDescription.Type);
//not perfect, crashes with some cases
var schema = context.SchemaRegistry.Definitions[idFor];
UpdateSchema(schema, (SchemaRegistry) context.SchemaRegistry, context.ApiParameterDescription.ModelMetadata);
}
}
catch (Exception e)
{
//eat because above is broken
}
}
private void UpdateSchema(Schema schema, SchemaRegistry schemaRegistry, ModelMetadata modelMetadata)
{
if (schema.Ref != null)
{
var schemaReference = schema.Ref.Replace("#/definitions/", "");
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
return;
}
if (schema.Properties == null) return;
foreach (var properties in modelMetadata.Properties)
{
if (properties is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name) == false) return;
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute) x).ToList();
var descriptionAttribute =
(DescriptionAttribute) attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
var displayAttribute = (DisplayAttribute) attributes.FirstOrDefault(x => x is DisplayAttribute);
if (displayAttribute != null)
subSchema.Title = displayAttribute.Name;
if (modelMetadata.ModelType.IsPrimitive) return;
UpdateSchema(subSchema, schemaRegistry, defaultModelMetadata);
}
}
}
}
Operation Filter
public class SwaggerOperationFilter : IOperationFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
private IModelMetadataProvider _metadataProvider;
public SwaggerOperationFilter(IModelMetadataProvider metadataProvider, SchemaRegistrySettings settings = null)
{
this._metadataProvider = metadataProvider;
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(Operation operation, OperationFilterContext context)
{
try
{
foreach (var paramDescription in context.ApiDescription.ParameterDescriptions)
{
if (paramDescription?.ModelMetadata?.Properties == null)
{
continue;
}
if (paramDescription.ModelMetadata.ModelType.IsPrimitive)
{
continue;
}
if (paramDescription.ModelMetadata.ModelType == typeof(string))
{
continue;
}
var idFor = _schemaIdManager.IdFor(paramDescription.Type);
var schema = context.SchemaRegistry.Definitions[idFor];
UpdateSchema(schema, (SchemaRegistry)context.SchemaRegistry, paramDescription.ModelMetadata);
}
}
catch (Exception e)
{
//eat because above is broken
}
}
private void UpdateSchema(Schema schema, SchemaRegistry schemaRegistry, ModelMetadata modelMetadata)
{
if (schema.Ref != null)
{
var schemaReference = schema.Ref.Replace("#/definitions/", "");
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
return;
}
if (schema.Type == "array")
{
if (schema.Items.Ref != null)
{
var schemaReference = schema.Items.Ref.Replace("#/definitions/", "");
var modelTypeGenericTypeArgument = modelMetadata.ModelType.GenericTypeArguments[0];
modelMetadata = _metadataProvider.GetMetadataForType(modelTypeGenericTypeArgument);
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
}
return;
}
if (schema.Properties == null) return;
foreach (var properties in modelMetadata.Properties)
{
if (properties is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name) == false) return;
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute)x).ToList();
var descriptionAttribute =
(DescriptionAttribute)attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
var displayAttribute = (DisplayAttribute)attributes.FirstOrDefault(x => x is DisplayAttribute);
if (displayAttribute != null)
subSchema.Title = displayAttribute.Name;
if (defaultModelMetadata.ModelType.IsPrimitive) return;
UpdateSchema(subSchema, schemaRegistry, defaultModelMetadata);
}
}
}
}
So after some troubleshooting this seems to work for me but may need modification for other cases.
public class SwashbuckleAttributeReaderDocumentFilter : IDocumentFilter
{
private readonly SchemaIdManager _schemaIdManager;
private readonly IModelMetadataProvider _metadataProvider;
private List<string> _updatedSchemeList;
public SwashbuckleAttributeReaderDocumentFilter(IModelMetadataProvider metadataProvider, SchemaRegistrySettings settings = null)
{
_metadataProvider = metadataProvider;
var registrySettings = settings ?? new SchemaRegistrySettings();
_schemaIdManager = new SchemaIdManager(registrySettings.SchemaIdSelector);
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
_updatedSchemeList = new List<string>();
foreach (var apiDescription in context.ApiDescriptions)
{
foreach (var responseTypes in apiDescription.SupportedResponseTypes)
{
ProcessModelMetadata(context, responseTypes.ModelMetadata);
}
foreach (var paramDescription in apiDescription.ParameterDescriptions)
{
ProcessModelMetadata(context, paramDescription.ModelMetadata);
}
}
}
private void ProcessModelMetadata(DocumentFilterContext context, ModelMetadata currentModelMetadata)
{
if (currentModelMetadata?.Properties == null)
{
return;
}
if (currentModelMetadata.ModelType.IsValueType)
{
return;
}
if (currentModelMetadata.ModelType == typeof(string))
{
return;
}
if (currentModelMetadata.ModelType.IsGenericType)
{
foreach (var modelType in currentModelMetadata.ModelType.GenericTypeArguments)
{
var modelMetadata = _metadataProvider.GetMetadataForType(modelType);
UpdateSchema(context.SchemaRegistry, modelMetadata);
}
}
else if (currentModelMetadata.IsCollectionType)
{
var modelType = currentModelMetadata.ModelType.GetElementType();
var modelMetadata = _metadataProvider.GetMetadataForType(modelType);
UpdateSchema(context.SchemaRegistry, modelMetadata);
}
else
{
UpdateSchema(context.SchemaRegistry, currentModelMetadata);
}
}
public static void SetSchema(Schema schema, ModelMetadata modelMetadata)
{
if (!(modelMetadata is DefaultModelMetadata metadata)) return;
var attributes = GetAtributes(metadata);
SetDescription(attributes, schema);
SetTitle(attributes, schema);
}
private static List<Attribute> GetAtributes(DefaultModelMetadata modelMetadata)
{
return modelMetadata.Attributes.Attributes.Select(x => (Attribute)x).ToList();
}
private static void SetTitle(List<Attribute> attributes, Schema schema)
{
//LastOrDefault because we want the attribute from the dervived class.
var displayAttribute = (DisplayNameAttribute)attributes.LastOrDefault(x => x is DisplayNameAttribute);
if (displayAttribute != null)
schema.Title = displayAttribute.DisplayName;
}
private static void SetDescription(List<Attribute> attributes, Schema schema)
{
//LastOrDefault because we want the attribute from the dervived class. not sure if this works.
var descriptionAttribute = (DescriptionAttribute)attributes.LastOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
schema.Description = descriptionAttribute.Description;
}
private void UpdateSchema(ISchemaRegistry schemaRegistry, ModelMetadata modelMetadata, Schema schema = null)
{
if (modelMetadata.ModelType.IsValueType) return;
if (modelMetadata.ModelType == typeof(string)) return;
var idFor = _schemaIdManager.IdFor(modelMetadata.ModelType);
if (_updatedSchemeList.Contains(idFor))
return;
if (schema == null || schema.Ref != null)
{
if (schemaRegistry.Definitions.ContainsKey(idFor) == false) return;
schema = schemaRegistry.Definitions[idFor];
}
_updatedSchemeList.Add(idFor);
SetSchema(schema, modelMetadata);
if (schema.Type == "array")//Array Schema
{
var metaData = _metadataProvider.GetMetadataForType(modelMetadata.ModelType.GenericTypeArguments[0]);
UpdateSchema(schemaRegistry, metaData);
}
else//object schema
{
if (schema.Properties == null)
{
return;
}
foreach (var properties in modelMetadata.Properties)
{
if (!(properties is DefaultModelMetadata defaultModelMetadata))
{
continue;
}
var name = ToLowerCamelCase(defaultModelMetadata.Name);
if (schema.Properties.ContainsKey(name) == false)
{
//when this doesn't match the json object naming.
return;
}
var subSchema = schema.Properties[name];
SetSchema(subSchema, defaultModelMetadata);
UpdateSchema(schemaRegistry, defaultModelMetadata, subSchema);
}
}
}
private static string ToLowerCamelCase(string inputString)
{
if (inputString == null) return null;
if (inputString == string.Empty) return string.Empty;
if (char.IsLower(inputString[0])) return inputString;
return inputString.Substring(0, 1).ToLower() + inputString.Substring(1);
}
}

Null pointer exception when processing Linked List nodes

package LinkList2;
//import java.util.*;
public class Duplicates {
public static void removeDuplicates(LinkedListNode head)
{
LinkedListNode current = head;
while(current!= null && current.next!= null)
{
LinkedListNode curr = current;
while(curr!=null)
{
if(curr.next.data==current.data) //Getting error at this line
curr.next = curr.next.next;
else
curr = curr.next;
}
current = current.next;
}
}
public static void main(String args[])
{
LinkedListNode first = new LinkedListNode(0,null,null);
LinkedListNode head = first;
LinkedListNode second = first;
for(int i=1; i< 8; i++)
{
second = new LinkedListNode(i%2, null, null);
first.setNext(second);
second.setPrevious(first);
}
System.out.println(head.printForward());
removeDuplicates(head);// Getting error at this line
}
}
Getting null pointer exception in the above code. When I try to run the above code, it gives null pointer exception.
Please help me with my mistake.
Below is the implementation of LinkList where all the methods are defined
class LinkedListNode {
public LinkedListNode next;
public LinkedListNode prev;
public LinkedListNode last;
public int data;
public LinkedListNode(int d, LinkedListNode n, LinkedListNode p) {
data = d;
setNext(n);
setPrevious(p);
}
public void setNext(LinkedListNode n) {
next = n;
if (this == last) {
last = n;
}
if (n != null && n.prev != this) {
n.setPrevious(this);
}
}
public void setPrevious(LinkedListNode p) {
prev = p;
if (p != null && p.next != this) {
p.setNext(this);
}
}
public String printForward() {
if (next != null) {
return data + "->" + next.printForward();
} else {
return ((Integer) data).toString();
}
}
public LinkedListNode clone() {
LinkedListNode next2 = null;
if (next != null) {
next2 = next.clone();
}
LinkedListNode head2 = new LinkedListNode(data, next2, null);
return head2;
}
}
You are getting an exception just because of the following condition:
while(curr != null)
Replace it with while(curr != null && curr.next != null) this way you can check if you have the next element.
Hope this helps.
The problem is that here:
while(curr != null)
{
if(curr.next.data==current.data) //Getting error at this line
curr.next = curr.next.next;
else
curr = curr.next;
}
You are accessing the curr.next.data where you are not checking if that node is null or not. This through your NullPointerException.
To fix your problem is to check on the while loop, if the .next is also not null.
while(curr != null && curr.next != null)
{
if(curr.next.data==current.data) //Getting error at this line
curr.next = curr.next.next;
else
curr = curr.next;
}
In other words, you are not checking if your next node is actually the end of the linked list (i.e null). If you need in your program logic to handle this separately, then you should remove the check from the while loop, and implement this check differently.

Scrolling with mouse Win 8.1 Metro Hub Navigation

I am trying to find a solution to allow a Hub to pan with the mouse when its reaches the left or right boundary. I have implemented the code below which i have gleaned from various sources.
` private void theHubPointerMoved(object sender, PointerRoutedEventArgs e)
{ Windows.UI.Xaml.Input.Pointer ptr = e.Pointer;
if (ptr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
{
Windows.UI.Input.PointerPoint ptrPt = e.GetCurrentPoint(null);
if (ptrPt.Position.X < this.ActualWidth - 20)
if (ptrPt.Position.X > 20)
{
//Do the SCROLLING HERE
var xcord = Math.Round(ptrPt.Position.X, 2);
var ycord = Math.Round(ptrPt.Position.Y, 2);
}
}
e.Handled = true;
}`
So it is relativley easy to see when the mouse is at the screen edge. I thought it would be easy to simply use the MyHub.ScrollViewer.ScrollToHorizontalOffset(xcord); but the Hub Scrollviewer doesnt expose this ScrollToHorizontalOffset function.
Can anyone assist?
Thanks.
Oh, it's exposed. If you can handle digging for it. Here's how:
http://xaml.codeplex.com/SourceControl/latest#Blog/201401-ScrollHub/MainPage.xaml.cs
In the example below, it is scrolling to a specific hub section. But you should be able to easily adapt it to your specific needs, I hope.
private void ScollHubToSection(Hub hub, HubSection section)
{
var visual = section.TransformToVisual(this.MyHub);
var point = visual.TransformPoint(new Point(0, 0));
var viewer = Helpers.FindChild<ScrollViewer>(hub, "ScrollViewer");
viewer.ChangeView(point.X, null, null);
}
Using this:
public class Helpers
{
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
foundChild = FindChild<T>(child, childName);
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
if (frameworkElement != null && frameworkElement.Name == childName)
{
foundChild = (T)child;
break;
}
}
else
{
foundChild = (T)child;
break;
}
}
return foundChild;
}
}
Best of luck!

How to write a custom FindElement routine in Selenium?

I'm trying to figure out how to write a custom FindElement routine in Selenium 2.0 WebDriver. The idea would be something like this:
driver.FindElement(By.Method( (ISearchContext) => {
/* examine search context logic here... */ }));
The anonymous method would examine the ISearchContext and return True if it matches; False otherwise.
I'm digging through the Selenium code, and getting a bit lost. It looks like the actual By.* logic is carried out server-side, not client side. That seems to be complicating matters.
Any suggestions?
I do a multi-staged search. I have a method that performs a try catch and then a method that gets the element. In theory you could do a try catch until instead of this way but I like this way better because of my setup.
public bool CheckUntil(IWebDriver driver, string selectorType, string selectorInfo)
{
int Timer = 160;
bool itemFound = false;
for (int i = 0; i < Timer; i++)
if(itemFound)
{
i = 0
}
else
{
Thread.Sleep(500);
if(selectorType.ToLower() == "id" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.Id(selectorInfo).Displayed)
{
itemFound = true;
}
}
else if(selectorType.ToLower() == "tagname" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.TagName(selectorInfo).Displayed)
{
itemFound = true;
}
}
}
return itemFound;
}
Here's my try catch method you can add as many different types as you want id, cssselector, xpath, tagname, classname, etc.
public bool TryCatch(IWebDriver driver, string selectorType, string selectorInfo)
{
bool ElementFound = false;
try
{
switch(selectorType)
{
case "id":
driver.FindElement(By.Id(selectorInfo);
break;
case "tagname":
driver.FindElement(By.TagName(selectorInfo);
break;
}
ElementFound = truel
}
catch
{
ElementFound = false;
}
return ElementFound;
}
Ok, I figured out how to do this. I'm leveraging driver.ExecuteScript() to run custom js on the webdriver. It looks a bit like this:
function elementFound(elem) {
var nodeType = navigator.appName == ""Microsoft Internet
Explorer"" ? document.ELEMENT_NODE : Node.ELEMENT_NODE;
if(elem.nodeType == nodeType)
{
/* Element identification logic here */
}
else { return false; }
}
function traverseElement(elem) {
if (elementFound(elem) == true) {
return elem;
}
else {
for (var i = 0; i < elem.childNodes.length; i++) {
var ret = traverseElement(elem.childNodes[i]);
if(ret != null) { return ret; }
}
}
}
return traverseElement(document);