entity framework 6.1 duplicate unique index exception handling - entity-framework-6.1

How can I handle duplicate key row with unique index SqlException using [Index(IsUnique = true)] attribute in entity framework 6.1?

So here is a quick hack
try
{
context.SaveChanges();
}
catch (DbUpdateException e)
{
SqlException innerException = null;
Exception tmp = e;
while(innerException == null && tmp!=null)
{
if (tmp != null)
{
innerException = tmp.InnerException as SqlException;
tmp = tmp.InnerException;
}
}
if (innerException != null && innerException.Number == 2601)
{
// handle exception
}
else
{
throw;
}
}
I hope there is a better solution...

You can override the ValidateEntity in your dbContext and do your logic here.
I've posted about generic way how to do it in CodeProject
Validate a Unique Constraint at dbContext ValidateEntity in Entity Framework

Related

Merging two identical word document displaying wrong page number using aspose word

Using Aspose Implementation:Aspose.Words for Java
Aspose Implementation-Version: 13.5.0.0
Below are the documents:
Source.docx
A1.docx
A2.docx
A3.docx
Using below code to append the word documents:
public static void main(String[] args) {
try {
List<Document> documentsToBeMerged=new ArrayList<Document>();
Document source=new Document("D:/Source.docx");
Document identicalDoc1=new Document("D:/A1.docx");
Document identicalDoc2=new Document("D:/A2.docx");
Document identicalDoc3=new Document("D:/A3.docx");
documentsToBeMerged.add(identicalDoc1);
documentsToBeMerged.add(identicalDoc2);
documentsToBeMerged.add(identicalDoc3);
mergeDocumentsWithSourceDocumentHeaderFooter(source, documentsToBeMerged, "D:/output.docx");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void mergeDocumentsWithSourceDocumentHeaderFooter(
Document destinationDocument, List<Document> mergingdocument,
String outputFileName) throws Exception {
try {
for (Document document : mergingdocument) {
document.getFirstSection().getPageSetup()
.setSectionStart(SectionStart.NEW_PAGE);
document.getFirstSection().getHeadersFooters()
.linkToPrevious(true);
destinationDocument.appendDocument(document,
ImportFormatMode.KEEP_SOURCE_FORMATTING);
}
AsposeUtil.convertNumPageFieldsToPageRef(destinationDocument);
destinationDocument.updatePageLayout();
destinationDocument.save(outputFileName);
} catch (Exception e) {
throw e;
}
}
public static void convertNumPageFieldsToPageRef(Document doc) throws Exception
{
final String BOOKMARK_PREFIX = "_SubDocumentEnd";
final String NUM_PAGES_FIELD_NAME = "NUMPAGES";
final String PAGE_REF_FIELD_NAME = "PAGEREF";
DocumentBuilder builder = new DocumentBuilder(doc);
int subDocumentCount = 0;
for (Section section : doc.getSections())
{
if (section.getPageSetup().getRestartPageNumbering())
{
if (!section.equals(doc.getFirstSection()))
{
Section prevSection = (Section)section.getPreviousSibling();
Node lastNode = prevSection.getBody().getLastChild();
builder.moveTo(lastNode);
builder.startBookmark(BOOKMARK_PREFIX + subDocumentCount);
builder.endBookmark(BOOKMARK_PREFIX + subDocumentCount);
subDocumentCount++;
}
}
if (section.equals(doc.getLastSection()))
{
Node lastNode = doc.getLastSection().getBody().getLastChild();
builder.moveTo(lastNode);
builder.startBookmark(BOOKMARK_PREFIX + subDocumentCount);
builder.endBookmark(BOOKMARK_PREFIX + subDocumentCount);
}
for (Node node : section.getChildNodes(NodeType.FIELD_START, true).toArray())
{
FieldStart fieldStart = (FieldStart)node;
if (fieldStart.getFieldType() == FieldType.FIELD_NUM_PAGES)
{
String fieldCode = getFieldCode(fieldStart);
String fieldSwitches = fieldCode.replace(NUM_PAGES_FIELD_NAME, "").trim();
Node previousNode = fieldStart.getPreviousSibling();
if (previousNode == null)
previousNode = fieldStart;
builder.moveTo(previousNode);
Field newField = builder.insertField(MessageFormat.format(" {0} {1}{2} {3} ", PAGE_REF_FIELD_NAME, BOOKMARK_PREFIX, subDocumentCount, fieldSwitches));
previousNode.getParentNode().insertBefore(previousNode, newField.getStart());
removeField(fieldStart);
}
}
}
}
private static String getFieldCode(FieldStart fieldStart) throws Exception
{
StringBuilder builder = new StringBuilder();
for (Node node = fieldStart; node != null && node.getNodeType() != NodeType.FIELD_SEPARATOR &&
node.getNodeType() != NodeType.FIELD_END; node = node.nextPreOrder(node.getDocument()))
{
if (node.getNodeType() == NodeType.RUN)
builder.append(node.getText());
}
return builder.toString();
}
private static void removeField(FieldStart fieldStart) throws Exception
{
Node currentNode = fieldStart;
boolean isRemoving = true;
while (currentNode != null && isRemoving)
{
if (currentNode.getNodeType() == NodeType.FIELD_END)
isRemoving = false;
Node nextNode = currentNode.nextPreOrder(currentNode.getDocument());
currentNode.remove();
currentNode = nextNode;
}
}
Issue: Total page output.docx contains 12 and last page footer is showing page number as 12 of 11 which is wrong.
Note: Both the documents Identical1.docx and Identical2.docx are same and also contains same References.
Please suggest me any solution how to resolve the page number issue.
We have tested the scenario using latest version of Aspose.Words for Java 18.6 and have not found the shared issue. Please use Aspose.Words for Java 18.6. Please note that Aspose.Words mimics the behavior of MS Word. If you join these documents using MS Word, the final output document will have 9 pages.
Moreover, please share the code of AsposeUtil.convertNumPageFieldsToPageRef method for further testing.
I work with Aspose as Developer Evangelist.

Sitecore.Analytics.Tracker.Current is null when invoked through a pipeline

I need to redirect based on the country location the user is trying to access. For example when user trying to access http://www.example.com/ from china my site should as http://www.example.com/zh. I am checking using the sitecore tracker in pipeline process to get the country code using the below method.
public void Process(HttpRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (HttpContext.Current == null
|| Context.Site == null
////TODO: || Sitecore.Context.PageMode...
|| Context.Database == null || Context.Site.Name == "shell" || !this._sites.Contains(Context.Site.Name))
{
return;
}
// contains path including language and query string
// (not anchor name), but not hostname.
// We can use this to add the language back into the path.
string rawPath = Sitecore.Context.RawUrl;
if (!rawPath.StartsWith("/sitecore") && !rawPath.StartsWith("/" + Sitecore.Context.Language.Name + "/") && !rawPath.StartsWith("/" + Sitecore.Context.Language.Name) && !rawPath.StartsWith("/default.aspx"))
{
string langCode = "";
if(!string.IsNullOrEmpty(GeoIPUtils.GetUserGeoIP()))
{
try
{
string country = GeoIPUtils.GetUserGeoIP();;
if (country.Trim().ToUpper() == "China".ToUpper())
langCode = "zh";
else if (country.Trim().ToUpper() == "Japan".ToUpper())
langCode = "jp";
else if (country.Trim().ToUpper() == "Thailand".ToUpper())
langCode = "th";
else
langCode = "en";
}
catch(Exception)
{
langCode = "en";
}
}
else
{
langCode = HttpContext.Current.Request.Cookies["avc#lang"].Value.ToString();
}
if (!string.IsNullOrEmpty(langCode))
{
Language language = null;
if (Language.TryParse(langCode, out language))
{
//then try to get the language item id from the language or two letter iso code
ID langID = LanguageManager.GetLanguageItemId(language, Sitecore.Context.Database);
if (!ID.IsNullOrEmpty(langID))
{
//sometimes the language found is slightly different than official language item used in SC
language = LanguageManager.GetLanguage(language.CultureInfo.TwoLetterISOLanguageName);
if (Context.Item != null)
{
List<string> availableLangs = LanguagesWithContent(Context.Item);
if (availableLangs != null && availableLangs.Count > 0 && !availableLangs.Contains(language.CultureInfo.TwoLetterISOLanguageName.ToString()))
{
langCode = availableLangs.FirstOrDefault().ToString();
}
}
else
{
langCode = "en";
}
}
else
{
langCode = "en";
}
}
}
HttpContext.Current.Response.RedirectPermanent("/" + (String.IsNullOrEmpty(langCode) ? Sitecore.Context.Language.Name : langCode) + rawPath);
}
}
Below is the GetUserGeoIP function
public static string GetUserGeoIP()
{
string countryCode = "";
try
{
countryCode = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.Country;
}
catch(Exception ex)
{
Log.Error("GetUserGeoIP Error: " + ex.Message + " Source: " + ex.Source + " Stack Trace :" + ex.StackTrace + " Inner Ex : " + ex.InnerException, ex);
countryCode = "GB";
}
if (!string.IsNullOrEmpty(countryCode))
{
var countryItem = ISO3166.FromAlpha2(countryCode);
if (countryItem != null)
return countryItem.Name;
}
return "Other";
}
But I am getting an below exception
7904 10:43:25 ERROR Cannot create tracker.
Exception: System.InvalidOperationException
Message: session is not initialized
Source: Sitecore.Analytics
at Sitecore.Analytics.Data.HttpSessionContextManager.GetSession()
at Sitecore.Analytics.Pipelines.EnsureSessionContext.EnsureContext.Process(InitializeTrackerArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Analytics.DefaultTracker.EnsureSessionContext()
at Sitecore.Analytics.Pipelines.CreateTracker.GetTracker.Process(CreateTrackerArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Analytics.Tracker.Initialize()
Note: The same GetUserGeoIP method is used in API which gets the correct countryName. I am using Sitecore.NET 8.0 (rev. 151127) version
Any help on this highly appreciated
Your processor is probably too soon in the pipeline(s). You can find an overview of the request pipelines here: http://sitecoreskills.blogspot.be/2015/02/a-sitecore-8-request-from-beginning-to.html
You should put your processor after the tracker has been initialized and the geo data has been fetched. I did something similar a while ago and placed my processor in the startAnalytics pipeline.
Fetching the geo data is async so that might (will) give issues when doing this in the first request pipeline. Read this article to tackle that issue by calling UpdateGeoIpData with a timespan.

print error while null value for SQL safety

How can I print "Error" while the JTextfield is empty
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String sn =jX1.getText();
if (sn==null){
System.out.println("Error");
System.out.println("T");
}
Thanks
Try using a fail-safe method. Also Expanding on the comments, you should be logging data, in a better format. Java hosts a huge array of different way to log certain data. look here
As for your error handling, try-catch-finally. This isn't tested code. Let me know if you run into any issues, documentation on try-catch and other statements here or here
public static void main(String[] args) {
while (String sn == null)
try {
String sn = JX1.getText();
} catch (Exception ex) {
System.out.println("Exception thrown!");
} finally {
if (sn != null) {
System.out.println("Closing PrintWriter");
sn.close();
} else {
System.out.println("PrintWriter not open");
}
}

Files locked after indexing

I have the following workflow in my (web)application:
download a pdf file from an archive
index the file
delete the file
My problem is that after indexing the file, it remains locked and the delete-part throws an exception.
Here is my code-snippet for indexing the file:
try
{
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
req.addFile(file, type);
req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
NamedList<Object> result = server.request(req);
Assert.assertEquals(0, ((NamedList<?>) result.get("responseHeader")).get("status"));
}
Do I miss something?
EDIT:
I tried this way too, but with the same result...
ContentStream contentStream = null;
try
{
contentStream = new ContentStreamBase.FileStream(document);
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest(UPDATE_EXTRACT_REQUEST);
// req.addFile(document, context.getProperty(FTSConstants.CONTENT_TYPE_APPLICATION_PDF));
req.addContentStream(contentStream);
req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
NamedList<Object> result = server.request(req);
if (!((NamedList<?>) result.get("responseHeader")).get("status").equals(0))
{
throw new IDSystemException(LOG, "Document could not be indexed. Status returned: " +
((NamedList<?>) result.get("responseHeader")).get("status"));
}
}
catch (FileNotFoundException fnfe)
{
throw new IDSystemException(LOG, fnfe.getMessage(), fnfe);
}
catch (IOException ioe)
{
throw new IDSystemException(LOG, ioe.getMessage(), ioe);
}
catch (SolrServerException sse)
{
throw new IDSystemException(LOG, sse.getMessage(), sse);
}
finally
{
try
{
if(contentStream != null && contentStream.getStream() != null)
{
contentStream.getStream().close();
}
}
catch (IOException ioe)
{
throw new IDSystemException(LOG, ioe.getMessage(), ioe);
}
}
This seems like a bug,
a patch is proposed here
https://issues.apache.org/jira/browse/SOLR-1744
Also checkout
http://lucene.472066.n3.nabble.com/ContentStreamUpdateRequest-addFile-fails-to-close-Stream-td485429.html
you can check if the stream is not null and close it.
It may be due to lock acquired by file system. Instead of addFile(), you can try the following.
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
ContentStreamBase.FileStream fileStream = new FileStream(file);
req.addContentStream(fileStream);
Shishir

How to update Target object from markup extension in SL5?

I'm trying this code in a markup extension in Silverlight 5.
public override object ProvideValue(IServiceProvider serviceProvider)
{
_target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
_depObj = _target.TargetObject as DependencyObject;
_depProp = _target.TargetProperty as DependencyProperty;
return GetText(TextId, DefaultText);
}
depObj seems to be provided correctly, however depProp seems not to be of type
DependencyProperty (The type is Sytem.String (of System.Reflection.PropertyInfo)). The cast results in null.
depProp is representing to the right Text or Content property, but without it being a
DependencyProperty I cannot set its value.
Any input greatly appreciated.
SiKo
Not sure why its coming up as a PropertyInfo but you can of course set the value with code something like:
if (TargetProperty is DependencyProperty)
{
var dependencyObject = target as DependencyObject;
if (dependencyObject != null)
{
var newValue = GetValue();
dependencyObject.SetValue(TargetProperty as DependencyProperty, newValue);
}
}
else if (TargetProperty is PropertyInfo)
{
var pi = target as PropertyInfo;
pi.SetValue(target, GetValue(), null);
}
The approach #Berryl gave above could work. But if you also need to get to the DependencyProperty, you can use something like this. This code also demonstrates the subtle differences between silverlight and WPF, but both can work great.
For silverlight or WPF only, you can remove the parts before or after the #else to simplify the code a little bit.
But the part that resolves the dependency property is in the middle (assigning _property).
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget Target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (Target == null) {
throw new InvalidOperationException(
"Cannot resolve the IProvideValueTarget. Are you binding to a property?");
}
/* we need the dependency property (for bindings) */
#if SILVERLIGHT
PropertyInfo Property = (PropertyInfo)Target.TargetProperty;
/* resolve the dependency property */
FieldInfo DepPropertyInfo = Target.TargetObject.GetType()
.GetField(Property.Name + "Property", BindingFlags.Static | BindingFlags.Public);
_property = (DependencyProperty)DepPropertyInfo.GetValue(/* obj = */ null);
#else
_property = Target.TargetProperty as DependencyProperty;
#endif
if (_property != null) {
#if SILVERLIGHT
if (Property.Name.StartsWith("Text")) {
UpdateSourceTrigger = UpdateSourceTrigger.Default;
#else
if (_property.Name.StartsWith("Text")) {
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
#endif
}
else {
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
}
}